Skip to content

Commit

Permalink
thread-safe wip
Browse files Browse the repository at this point in the history
  • Loading branch information
Craftingmod committed Feb 27, 2018
1 parent 022d789 commit 68051df
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 60 deletions.
5 changes: 1 addition & 4 deletions src/main/java/net/tarks/craftingmod/nccauth/Main.java
Expand Up @@ -31,10 +31,7 @@ public static void main(String[] args){
}

private Gson g;
private Main _this;
private DiscordPipe discord;
public Main(String[] args){
_this = this;
g = new GsonBuilder().create();

File config_file = new File(Util.getRootdir(),"config.json");
Expand Down Expand Up @@ -94,7 +91,7 @@ public Main(String[] args){

getComments(cfg,-1); // 5 hours?

discord = new DiscordPipe(cfg,this);
DiscordPipe discord = new DiscordPipe(cfg,this);
}
public Config getNaverConfig(String id){
Config out = new Config("Please type discord bot token here.","Cafe URL..");
Expand Down
103 changes: 57 additions & 46 deletions src/main/java/net/tarks/craftingmod/nccauth/discord/AuthQueue.java
Expand Up @@ -12,16 +12,15 @@
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;

public abstract class AuthQueue extends ListenerAdapter implements Runnable {
public static long limit_minute = 10;
protected ICommander cmd;
protected final ICommander cmd;
protected Config cfg;
protected Gson g;
protected final Gson g;

protected final Object lock;

private ArrayList<DiscordUser> queue;
private HashMap<Long,Long> timelimit_sec;
Expand All @@ -32,36 +31,41 @@ public AuthQueue(Config c,ICommander cmd){
this.cfg = c;

g = new GsonBuilder().create();
lock = new Object();

queue = new ArrayList<>();
timelimit_sec = new HashMap<>();
service = Executors.newScheduledThreadPool(2);
//service = Executors.newScheduledThreadPool(2);
service = Executors.newSingleThreadScheduledExecutor();

final Runnable _this = this;
service.scheduleAtFixedRate(() -> service.execute(_this), 0, 10, TimeUnit.SECONDS);
//service.scheduleAtFixedRate(() -> service.execute(_this), 0, 10, TimeUnit.SECONDS);
service.scheduleWithFixedDelay(this,0,10,TimeUnit.SECONDS);
}

protected int requestAuth(long discordUID,long saidChannel){
return requestAuth(new DiscordUser(discordUID,saidChannel));
}
protected int requestAuth(DiscordUser discordUser){
if(timelimit_sec.containsKey(discordUser.userID)){
return (int) Math.min((Instant.now().getEpochSecond()-timelimit_sec.get(discordUser.userID)),-1);
}
ArrayList<Integer> tokens = new ArrayList<>();
for(DiscordUser du : queue){
tokens.add(du.token);
}
int token;
do {
token = (int) Math.floor(Math.random() * 900000) + 100000;
} while(tokens.contains(token));
synchronized (lock){
if(timelimit_sec.containsKey(discordUser.userID)){
return (int) Math.min((Instant.now().getEpochSecond()-timelimit_sec.get(discordUser.userID)),-1);
}
ArrayList<Integer> tokens = new ArrayList<>();
for(DiscordUser du : queue){
tokens.add(du.token);
}
int token;
do {
token = (int) Math.floor(Math.random() * 900000) + 100000;
} while(tokens.contains(token));

discordUser.token = token;
Instant now = Instant.now();
queue.add(discordUser);
timelimit_sec.put(discordUser.userID,now.plus(limit_minute, ChronoUnit.MINUTES).getEpochSecond());
return token;
discordUser.token = token;
Instant now = Instant.now();
queue.add(discordUser);
timelimit_sec.put(discordUser.userID,now.plus(limit_minute, ChronoUnit.MINUTES).getEpochSecond());
return token;
}
}

protected abstract void onAuthResult(ArrayList<DiscordUser> users);
Expand All @@ -75,31 +79,38 @@ public void run() {
// huge resource
Instant now = Instant.now();

ArrayList<Comment> comments = cmd.getComments(cfg,60 * limit_minute);
for(int i=0;i<queue.size();i+=1){
DiscordUser user = queue.get(i);
if(now.getEpochSecond() >= timelimit_sec.get(user.userID)){
user.token = -1 * (int)limit_minute;
changed.add(user);
queue.remove(user);
timelimit_sec.remove(user.userID);
continue;
}
for(Comment c : comments){
if(c.content.startsWith(Integer.toString(user.token))){
if((user.cafeID != null && c.userID.equalsIgnoreCase(user.cafeID)) || (user.username != null && c.nickname.equals(user.username)) || (user.cafeID == null && user.username == null)){
user.cafeID = c.userID;
user.username = c.nickname;
changed.add(user);
queue.remove(user);
timelimit_sec.remove(user.userID);
break;
// no need to synchronized : cmd;
ArrayList<Comment> comments = cmd.getComments(cfg,60 * limit_minute); // waiting..

synchronized (lock){
for(int i=0;i<queue.size();i+=1){
DiscordUser user = queue.get(i);
if(now.getEpochSecond() >= timelimit_sec.get(user.userID)){
user.token = -1 * (int)limit_minute;
changed.add(user);
queue.remove(user);
timelimit_sec.remove(user.userID);
continue;
}
for(Comment c : comments){
if(c.content.startsWith(Integer.toString(user.token))){
if((user.cafeID != null && c.userID.equalsIgnoreCase(user.cafeID)) || (user.username != null && c.nickname.equals(user.username)) || (user.cafeID == null && user.username == null)){
user.cafeID = c.userID;
user.username = c.nickname;
changed.add(user);
queue.remove(user);
timelimit_sec.remove(user.userID);
break;
}
}
}
}
if(changed.size() >= 1){
onAuthResult(changed);
}
}
if(changed.size() >= 1){
onAuthResult(changed);
}
}
public interface onTokenListener {
void onTokenGenerated(int token);
}
}
Expand Up @@ -91,6 +91,7 @@ protected Game getGame(String title,long gametype){
}

/**
* synchronized by sub thread(caller: AuthQueue)
* Event on auth success or fail(token = -1)
* @param users
*/
Expand Down Expand Up @@ -183,9 +184,12 @@ public void guildMemberLeave(Guild g,User u){
msg = msg.replace("$username",u.getName());
g.getTextChannelById(cfg.discordBotChID).sendMessage(msg).queue();
long id = u.getIdLong();
if(authlist.list.containsKey(id)){
authlist.list.remove(id);
authlist.save();

synchronized (lock){
if(authlist.list.containsKey(id)){
authlist.list.remove(id);
authlist.save();
}
}
}

Expand All @@ -195,8 +199,9 @@ public void guildMemberLeave(Guild g,User u){
*/
@Override
public void onMessageReceived(MessageReceivedEvent event) {
execCommand(event);

synchronized (lock) {
execCommand(event);
}
if (event.isFromType(ChannelType.PRIVATE))
{
System.out.printf("[PM] %s: %s\n", event.getAuthor().getName(),
Expand All @@ -208,6 +213,12 @@ public void onMessageReceived(MessageReceivedEvent event) {

}
}

/**
* Synchronized by main thread
* onMessageReceived
* @param event
*/
public void execCommand(MessageReceivedEvent event){
if(!event.getMessage().isFromType(ChannelType.VOICE)){
User sender = event.getAuthor();
Expand Down
2 changes: 1 addition & 1 deletion target/maven-archiver/pom.properties
@@ -1,5 +1,5 @@
#Generated by Maven
#Tue Feb 27 14:18:02 KST 2018
#Tue Feb 27 23:10:16 KST 2018
version=1.0.0
groupId=net.tarks.craftingmod
artifactId=ncc_auth
@@ -1,12 +1,13 @@
net/tarks/craftingmod/nccauth/discord/DiscordPipe.class
net/tarks/craftingmod/nccauth/discord/ICommander.class
net/tarks/craftingmod/nccauth/discord/DiscordUser.class
net/tarks/craftingmod/nccauth/UserCafeDB.class
net/tarks/craftingmod/nccauth/Comment.class
net/tarks/craftingmod/nccauth/Main$1.class
net/tarks/craftingmod/nccauth/Util.class
net/tarks/craftingmod/nccauth/discord/AuthQueue.class
net/tarks/craftingmod/nccauth/discord/ICommander.class
net/tarks/craftingmod/nccauth/Config.class
net/tarks/craftingmod/nccauth/discord/DiscordUser.class
net/tarks/craftingmod/nccauth/discord/AuthQueue$onTokenListener.class
net/tarks/craftingmod/nccauth/Main.class
net/tarks/craftingmod/nccauth/discord/DiscordPipe$1.class
net/tarks/craftingmod/nccauth/discord/InitListener.class
net/tarks/craftingmod/nccauth/UserCafeDB.class
net/tarks/craftingmod/nccauth/Comment.class

0 comments on commit 68051df

Please sign in to comment.