aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/data/Account.java
blob: e540de445946809ebfe7bd59363f95cac28702b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2012-2014 lacolaco.net
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package net.lacolaco.smileessence.data;

import com.github.gfx.android.orma.annotation.Column;
import com.github.gfx.android.orma.annotation.PrimaryKey;
import com.github.gfx.android.orma.annotation.Table;
import net.lacolaco.smileessence.entity.DirectMessage;
import net.lacolaco.smileessence.entity.SavedSearch;
import net.lacolaco.smileessence.entity.Tweet;
import net.lacolaco.smileessence.entity.User;
import net.lacolaco.smileessence.twitter.task.Accounts;
import net.lacolaco.smileessence.twitter.task.Searches;
import net.lacolaco.smileessence.twitter.task.Users;
import net.lacolaco.smileessence.util.BackgroundTask;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Table
public class Account {
    private static Map<Long, Account> cache; // model id -> Account
    private User user;
    private final Set<String> listSubscriptions = Collections.newSetFromMap(new ConcurrentHashMap<>());
    private final Set<Long> muteUserIds = Collections.newSetFromMap(new ConcurrentHashMap<>());

    @PrimaryKey
    public long userId;
    @Column
    public String screenName;
    @Column
    public String oauthToken;
    @Column
    public String oauthTokenSecret;

    public Account() {
    }

    // --------------------- static methods ---------------------
    public static synchronized Account get(long i) {
        if (cache == null) {
            throw new IllegalStateException("Load first");
        }
        return cache.get(i);
    }

    public static synchronized int count() {
        return cache.size();
    }

    public static synchronized List<Account> all() {
        return new ArrayList<>(cache.values());
    }

    public static synchronized void load() {
        cache = new LinkedHashMap<>();
        for (Account item : relation().selector())
            cache.put(item.userId, item);
    }

    private static Account_Relation relation() {
        OrmaDatabase orma = OrmaHolder.getORMA();
        return orma.relationOfAccount();
    }

    public static synchronized Account register(String token, String tokenSecret, long userId, String screenName) {
        Account account = null;
        for (Account a : all()) {
            if (a.getUserId() == userId) {
                account = a;
                break;
            }
        }
        if (account == null)
            account = new Account();
        account.userId = userId;
        account.screenName = screenName;
        account.oauthToken = token;
        account.oauthTokenSecret = tokenSecret;

        relation().upserter().execute(account);

        cache.put(account.userId, account);

        return account;
    }

    public static synchronized Account unregister(long id) {
        Account account = cache.remove(id);
        if (account != null) {
            relation().deleter().userIdEq(id).execute();
        }
        return account;
    }

    public long getUserId() {
        return userId;
    }

    public Twitter getTwitter() {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setTweetModeExtended(true);
        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        twitter.setOAuthAccessToken(new AccessToken(oauthToken, oauthTokenSecret));
        return twitter;
    }

    public TwitterStream getTwitterStream() {
        TwitterStream stream = new TwitterStreamFactory().getInstance();
        stream.setOAuthAccessToken(new AccessToken(oauthToken, oauthTokenSecret));
        return stream;
    }

    public User getUser() {
        if (user == null) {
            user = User.fetch(userId);
            if (user == null) {
                user = User._makeSkeleton(userId, screenName);
            }
            user.addObserver(this, (objs) -> {
                if (!screenName.equals(user.getScreenName())) {
                    screenName = user.getScreenName();
                    relation().upserter().execute(this);
                }
            });
        }

        return user;
    }
    // --------------------- Helper methods ---------------------

    public boolean canDelete(Tweet tweet) {
        return tweet.getOriginalTweet().getUser() == getUser();
    }

    public boolean canDelete(DirectMessage message) {
        return message.getSender() == getUser() ||
                message.getRecipient() == getUser();
    }

    // --------------------- List subscription cache ---------------------
    public BackgroundTask<List<String>, Void> refreshListSubscriptions() {
        return new Users.GetManyTask(this)
                .onDone(lists -> {
                    listSubscriptions.clear();
                    listSubscriptions.addAll(lists);
                })
                // .onFail(x -> { }) // TODO: error message?
                .execute();
    }

    public Set<String> getListSubscriptions() {
        return listSubscriptions;
    }

    public boolean addListSubscription(String fullName) {
        return listSubscriptions.add(fullName);
    }

    public boolean removeListSubscription(String fullName) {
        return listSubscriptions.remove(fullName);
    }

    // --------------------- User mute cache ---------------------
    public List<BackgroundTask> refreshUserMuteList() {
        List<BackgroundTask> tasks = new ArrayList<>();
        tasks.add(new Accounts.BlockIDsTask(this).onDone(muteUserIds::addAll).execute());
        tasks.add(new Accounts.MutesIDsTask(this).onDone(muteUserIds::addAll).execute());
        return tasks;
    }

    public boolean isMutedUserListContains(long id) {
        return muteUserIds.contains(id);
    }

    public BackgroundTask<List<SavedSearch>, Void> refreshSavedSearches() {
        return new Searches.GetAllSavedSearchesTask(this).onDone(SavedSearch::replace).execute();
    }
}