Advertisement
Guest User

Untitled

a guest
May 28th, 2016
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.88 KB | None | 0 0
  1. package com.kaanaxinc.portalstudio;
  2.  
  3. import android.app.Activity;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothSocket;
  7. import android.content.Intent;
  8. import android.os.Bundle;
  9. import android.os.Handler;
  10. import android.os.ParcelUuid;
  11. import android.os.StrictMode;
  12. import android.text.Editable;
  13. import android.text.TextWatcher;
  14. import android.util.Log;
  15. import android.view.KeyEvent;
  16. import android.view.View;
  17. import android.view.View.OnClickListener;
  18. import android.view.View.OnKeyListener;
  19. import android.widget.Button;
  20. import android.widget.EditText;
  21. import android.widget.ImageButton;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24.  
  25. import java.io.BufferedReader;
  26. import java.io.FileInputStream;
  27. import java.io.FileNotFoundException;
  28. import java.io.FileOutputStream;
  29. import java.io.FileReader;
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.io.InputStreamReader;
  33. import java.io.OutputStream;
  34. import java.io.OutputStreamWriter;
  35. import java.net.URL;
  36. import java.net.URLConnection;
  37. import java.util.ArrayList;
  38. import java.util.Set;
  39.  
  40. public class MainActivity extends Activity {
  41. // La chaîne de caractères par défaut
  42. private final String defaut = "Le code d'accès est inscrit sur la notice.";
  43. Toast myToast;
  44. Button sendPost = null;
  45. Button sendComment = null;
  46. ImageButton logo = null;
  47. EditText codeEntered = null;
  48. TextView entrezCode = null;
  49. TextView codeSurNotice = null;
  50. TextView codeAEteChange = null;
  51. TextView texteRecu = null;
  52. Handler bluetoothIn;
  53. boolean currentView = false;
  54. final int handlerState = 0;
  55. String messageFinal = "jmesoiejsmoi";
  56.  
  57. BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
  58. private OutputStream outputStream;
  59. private InputStream inStream;
  60. ArrayList<String> postIds = new ArrayList<String>();
  61. int postNumber = 0;
  62. String subreddit = "skymine_";
  63.  
  64. String connectionError = "PortalStudio n'a pas pu se connecter au portail. Vérifiez votre connexion bluetooth. Tapez sur le logo pour réessayer la connexion.";
  65.  
  66. private void init() throws IOException {
  67. Thread connexionThread = new Thread(new Runnable()
  68. {
  69. public void run() {
  70. try {
  71. if (blueAdapter != null) {
  72. if (blueAdapter.isEnabled()) {
  73. Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
  74.  
  75. if(bondedDevices.size() > 0){
  76. BluetoothDevice bt2 = null;
  77. for(BluetoothDevice bt : bondedDevices) {
  78. bt2 = bt;
  79. }
  80.  
  81.  
  82. BluetoothDevice device = bt2;
  83. ParcelUuid[] uuids = device.getUuids();
  84. BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
  85. socket.connect();
  86. outputStream = socket.getOutputStream();
  87. inStream = socket.getInputStream();
  88. }
  89.  
  90. Log.e("error", "No appropriate paired devices.");
  91. }else{
  92. Log.e("error", "Bluetooth is disabled.");
  93. }
  94. }
  95. } catch (IOException e) {
  96.  
  97. }
  98. }
  99. });
  100.  
  101. connexionThread.start();
  102.  
  103. }
  104.  
  105. public void write(String s) throws IOException, NullPointerException {
  106. outputStream.write(s.getBytes());
  107. }
  108.  
  109. void beginListenForData() {
  110. Thread workerThread = new Thread(new Runnable()
  111. {
  112. public void run() {
  113.  
  114. byte[] buffer = new byte[256];
  115. int bytes;
  116.  
  117. while(!Thread.currentThread().isInterrupted()) {
  118. try {
  119. bytes = inStream.read(buffer); //read bytes from input buffer
  120. String readMessage = new String(buffer, 0, bytes);
  121. // Send the obtained bytes to the UI Activity via handler
  122. bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
  123. } catch (IOException e) {
  124. break;
  125. } catch (NullPointerException e) {
  126. toast("Null pointer exception 3");
  127. break;
  128. }
  129. }
  130. }
  131. });
  132.  
  133. workerThread.start();
  134. }
  135.  
  136. void checkBluetooth() {
  137. //Prompt user to turn on Bluetooth if Bluetooth is disabled
  138. if (!blueAdapter.isEnabled()) {
  139. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  140. startActivityForResult(enableBtIntent, 1);
  141. }
  142.  
  143. try {
  144. init();
  145. } catch (IOException e2) {
  146.  
  147. }
  148. }
  149.  
  150.  
  151.  
  152. void toast(String str) {
  153. myToast.setText(str);
  154. myToast.show();
  155. }
  156.  
  157.  
  158.  
  159.  
  160.  
  161. @Override
  162. public void onCreate(Bundle savedInstanceState) {
  163. super.onCreate(savedInstanceState);
  164. setContentView(R.layout.activity_main);
  165. myToast = Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT);
  166. // On récupère toutes les vues dont on a besoin
  167. sendPost = (Button)findViewById(R.id.sendPost);
  168. sendComment = (Button)findViewById(R.id.sendComment);
  169. codeSurNotice = (TextView)findViewById(R.id.codeSurNotice);
  170. entrezCode = (TextView)findViewById(R.id.entrezCode);
  171. texteRecu = (TextView)findViewById(R.id.texteRecu);
  172. // On attribue un listener adapté aux vues qui en ont besoin
  173. logo = (ImageButton)findViewById(R.id.logo);
  174. logo.setOnClickListener(logoListener);
  175. sendPost.setOnClickListener(sendPostListener);
  176. sendComment.setOnClickListener(sendCommentListener);
  177. if (android.os.Build.VERSION.SDK_INT > 9) {
  178. StrictMode.ThreadPolicy policy =
  179. new StrictMode.ThreadPolicy.Builder().permitAll().build();
  180. StrictMode.setThreadPolicy(policy);
  181. }
  182. //codeEntered.addTextChangedListener(textWatcher);
  183. //codeAEteChange.setVisibility(View.GONE);
  184. checkBluetooth();
  185.  
  186. /*try {
  187. FileInputStream fIn = openFileInput("codefile.txt");
  188. InputStreamReader isr = new InputStreamReader(fIn);
  189.  
  190. char[] inputBuffer = new char[4];
  191. isr.read(inputBuffer);
  192.  
  193. // Transform the chars to a String
  194. String readString = new String(inputBuffer);
  195. code = readString;
  196. } catch (FileNotFoundException e) {
  197. } catch (IOException e) {
  198. toast("PortalStudio a trouvé le fichier, mais n'a pas pu le lire");
  199. }*/
  200. bluetoothIn = new Handler() {
  201. public void handleMessage(android.os.Message msg) {
  202. if (msg.what == handlerState) {
  203. toast(messageFinal);
  204. messageFinal += (String) msg.obj; //for some reason removing the + causes it to remove the first character
  205. texteRecu.setText(messageFinal);
  206.  
  207. }
  208. }
  209. };
  210.  
  211. }
  212.  
  213. @Override
  214. public void onResume() {
  215. super.onResume();
  216. // connection methods are best here in case program goes into the background etc
  217. checkBluetooth();
  218. }
  219.  
  220.  
  221. private TextWatcher textWatcher = new TextWatcher() {
  222.  
  223. @Override
  224. public void onTextChanged(CharSequence s, int start, int before, int count) {
  225. codeSurNotice.setText(defaut);
  226. }
  227. @Override
  228. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  229.  
  230. }
  231. @Override
  232. public void afterTextChanged(Editable s) {
  233.  
  234. }
  235. };
  236.  
  237. // Uniquement pour le bouton "envoyer"
  238. private OnClickListener logoListener = new OnClickListener() {
  239. @Override
  240. public void onClick(View v) {
  241. codeSurNotice.setText("Connexion en cours...");
  242. try {
  243. init();
  244. } catch (IOException e2) {
  245.  
  246. }
  247. codeSurNotice.setText(defaut);
  248. }
  249. };
  250.  
  251. private OnClickListener sendPostListener = new OnClickListener() {
  252. @Override
  253. public void onClick(View v) {
  254. currentView = true;
  255. messageFinal = "";
  256. if (inStream != null) {
  257. beginListenForData();
  258.  
  259. String aEnvoyer;
  260.  
  261. if (currentView)
  262. aEnvoyer = getPost("https://reddit.com/r/" + subreddit + ".json") + "\"";
  263. else
  264. aEnvoyer = "<p test post> <1 test comment> <2 test second comment>\"\n";
  265.  
  266. try {
  267. write(aEnvoyer);
  268. } catch (IOException e) {
  269.  
  270. } catch (NullPointerException e) {
  271. toast(connectionError);
  272. }
  273. } else {
  274. toast(connectionError);
  275. }
  276.  
  277.  
  278. }
  279. };
  280.  
  281. private OnClickListener sendCommentListener = new OnClickListener() {
  282. @Override
  283. public void onClick(View v) {
  284. currentView = false;
  285. messageFinal = "";
  286. if (inStream != null) {
  287. beginListenForData();
  288.  
  289. String aEnvoyer;
  290.  
  291. if (currentView)
  292. aEnvoyer = "<r /r/the_donald> <p t=YOU CAN'T STUMP THE TRUMP\" a=/r/the_donald 4324 upvotes>Z";
  293. else
  294. aEnvoyer = "<r " + subreddit + "> " + getComments("https://reddit.com/" + postIds.get(postNumber) + ".json");
  295. toast(postIds.get(postNumber));
  296.  
  297. try {
  298. write(aEnvoyer);
  299. } catch (IOException e) {
  300.  
  301. } catch (NullPointerException e) {
  302. toast(connectionError);
  303. }
  304. } else {
  305. toast(connectionError);
  306. }
  307.  
  308.  
  309. }
  310. };
  311.  
  312. String getComments(String url) {
  313.  
  314. String str = "test";
  315. try {
  316. str = getText(url);
  317. } catch (Exception e) {}
  318. toast(str);
  319. String result = "";
  320. String textPostContent = "";
  321. String commentText = "";
  322. String commentAuthor = "";
  323. String commentScore = "";
  324. String[] jsonAttributes = {"selftext", "title"};
  325. String[] cmtVars = {commentAuthor, commentScore, commentText};
  326. String[] cmtAttributes = {"replies", "author", "score", "body"};
  327.  
  328. ArrayList<Integer> commentLvls = new ArrayList<Integer>();
  329. int currentComment = -1;
  330. //first, browse through the string
  331. int commentLvl = 1; //that way it's set to 1 after the }}], "after" of the text post
  332.  
  333. System.out.println("Beginning comment level analysis");
  334. for (int i = 10; i < str.length(); i++) {
  335. //System.out.println(str.substring(i-1, i+11));
  336. if (str.startsWith("}}], \"after\"", i)) {
  337. commentLvl--;
  338. /*String tabs = "";
  339. for (int j = 0; j < commentLvl; j++)
  340. tabs += "\t";
  341. System.out.println(tabs + "End of comment found. lvl = " + commentLvl);*/
  342. } else if (str.startsWith("[{\"kind\": \"t1\"", i)) {
  343. commentLvl++;
  344. commentLvls.add(commentLvl);
  345. //commentLvl++;
  346.  
  347. } else if (str.startsWith(" {\"kind\": \"t1\"", i)) {
  348. commentLvls.add(commentLvl);
  349. }
  350.  
  351. }
  352.  
  353.  
  354. /*boolean containsReplies = false;
  355. boolean isReply = false;
  356. boolean nextCmtIsALvlDown = false;*/
  357.  
  358. for (int i = 0; i < str.length(); i++) {
  359. if (str.startsWith("{\"kind\": \"t3\"", i)) {
  360. int j = 0;
  361. while (!str.substring(i - 1, i + 11).equals("}}], \"after\"")) {
  362. i++;
  363. if (j < jsonAttributes.length && str.startsWith("\"" + jsonAttributes[j] + "\": ", i)) {
  364. i += jsonAttributes[j].length() + 4;
  365. int end = 0;
  366. i++;
  367. end = i;
  368. while (!str.substring(end - 1, end + 3).equals("\", \"")) {
  369. //System.out.println(str.substring(end-1, end+3));
  370. end++;
  371. }
  372. end--;
  373. if (j == 1)
  374. textPostContent = str.substring(i, end) + "\n" + textPostContent;
  375. else
  376. textPostContent += str.substring(i, end);
  377. //System.out.println("test2 " + postAttributes[j]);
  378. //System.out.println("test" + jsonAttributes[j]);
  379. j++;
  380. }
  381. }
  382. result += "<t " + textPostContent + "> \n";
  383. } else if (str.startsWith("{\"kind\": \"t1\"", i)) {
  384. currentComment++;
  385. /*if (containsReplies)
  386. isReply = true;
  387. else if (str.charAt(i-1) == '[')
  388. isReply = false;*/
  389. //System.out.println("*****************************\nComment found.");
  390. //System.out.println(str.charAt(i-1));
  391. //System.out.println("is reply = " + isReply);
  392. //System.out.println("previous comment contains replies : " + containsReplies);
  393. int l = i;
  394. int j = 0;
  395. int k = 0;
  396. while (!str.substring(l - 1, l + 11).equals("}}], \"after\"")
  397. && !str.substring(l - 1, l + 16).equals("}}, {\"kind\": \"t1\"")) {
  398. l++;
  399. if (j < cmtAttributes.length && str.startsWith("\"" + cmtAttributes[j] + "\": ", l)) {
  400. l += cmtAttributes[j].length() + 4;
  401.  
  402. //l++;
  403. int end = l;
  404. //System.out.println("Attribute found: " + cmtAttributes[j]);
  405. if (j == 0) {
  406.  
  407. //System.out.println("Skipping possible child comments.");
  408. l += 57;
  409. //System.out.println(str.substring(l));
  410. //containsReplies = false;
  411. do {
  412. if (str.startsWith("{\"kind\": \"t1\"", l)) {
  413. k++;
  414. //containsReplies = true; //if there are replies then the comment level goes up
  415. //System.out.println("Child comment found, lvl " + (commentLvl+k));
  416. }
  417. if (str.startsWith("}}], \"after\"", l)) {
  418. k--;
  419. //System.out.println("Child comment finished, k = " + k);
  420. }
  421. if (str.startsWith("}}, {\"kind\": \"t1\"", l)) {
  422. //System.out.println("Child comment finished, another one found. k = " + k);
  423. l += 10;
  424. }
  425. l++;
  426. } while (k != 0);
  427. l++;
  428. } else {
  429. if (j != 2) {
  430. while (!str.substring(end - 1, end + 3).equals("\", \"")) {
  431. //System.out.println(str.substring(end-1, end+3));
  432. end++;
  433. }
  434. end--;
  435. l++;
  436. } else {
  437. end = str.indexOf(',', l);
  438. //end--;
  439. }
  440. //end--;
  441. cmtVars[j - 1] = str.substring(l, end);
  442. }
  443. j++;
  444. }
  445. }
  446. /*if (isReply)// && !str.substring(l-1, l+11).equals("}}], \"after\""))
  447. if (nextCmtIsALvlDown)
  448. commentLvl--;
  449. else
  450. commentLvl++;
  451. else // if (!isReply)// if (str.charAt(i-1) == '[')
  452. commentLvl = 0;
  453.  
  454. if (str.substring(l-1, l+11).equals("}}], \"after\""))
  455. nextCmtIsALvlDown = true;*/
  456. result += "<" + commentLvls.get(currentComment) + " " + cmtVars[2]
  457. + "\n/u/" + cmtVars[0] + " " + cmtVars[1] + " upvotes>";
  458. }
  459. }
  460. result = modifyText(result);
  461. return result + "\"";
  462. }
  463.  
  464. String getPost(String url) {
  465. String str = "test";
  466. do {
  467. /*new Thread( new Runnable() {
  468.  
  469. }).start();*/
  470. try {
  471. str = getText(url);
  472. } catch (Exception e) {}
  473. } while (str.equals("test"));
  474. toast(str);
  475. //toast ("Finished getting text");
  476.  
  477. String posts = "";
  478. String currentPostTitle = "";
  479. String currentPostUser = "";
  480. String currentPostId = "";
  481. String currentPostSub = "";
  482. String currentPostUrl = "";
  483. String currentPostScore = "";
  484. String currentPostCmts = "";
  485. String[] postAttributes = {currentPostUrl, currentPostSub, currentPostId, currentPostUser, currentPostScore, currentPostCmts, currentPostTitle};
  486. String[] jsonAttributes = {"domain", "subreddit", "id", "author", "score", "num_comments", "title"};
  487.  
  488. for (int i = 0; i < str.length(); i++) {
  489. if (str.startsWith("{\"kind\": \"t3\"", i)) {
  490. int j = 0;
  491. while (!str.substring(i - 1, i + 27).equals("}}, {\"kind\": \"t3\", \"data\": {")
  492. && !str.substring(i - 1, i + 11).equals("}}], \"after\"")) {
  493. i++;
  494. if (j < jsonAttributes.length && str.startsWith("\"" + jsonAttributes[j] + "\": ", i)) {
  495. i += jsonAttributes[j].length() + 4;
  496. int end = 0;
  497. if (j == 4 || j == 5)
  498. end = str.indexOf(',', i);
  499. else {
  500. i++;
  501. end = i;
  502. while (!str.substring(end - 1, end + 3).equals("\", \"")) {
  503. //System.out.println(str.substring(end-1, end+3));
  504. end++;
  505. }
  506. end--;
  507. }
  508. postAttributes[j] = str.substring(i, end);
  509. //System.out.println("test2 " + postAttributes[j]);
  510. //System.out.println("test" + jsonAttributes[j]);
  511. j++;
  512. }
  513. }
  514. //System.out.println("fin de post");
  515. if (postAttributes[0].startsWith("self."))
  516. postAttributes[0] = "self";
  517. else
  518. postAttributes[0] = "ext.link";
  519. postIds.add(postAttributes[2]);
  520. posts += "<p " + postAttributes[6] + "\n" + postAttributes[0] + " /r/" + postAttributes[1]
  521. + " /u/" + postAttributes[3] + " " + postAttributes[4] + " upvotes " + postAttributes[5] + " comments>\n";
  522. }
  523.  
  524. }
  525. //toast("Finished result");
  526. return posts + "\"";
  527. }
  528.  
  529. public String getText(String url) throws Exception {
  530. //toast("Trying to connect to " + url);
  531. URL website = new URL(url);
  532. URLConnection connection = website.openConnection();
  533. connection.setRequestProperty("User-Agent", "android:com.zezombye.caddit:v1.0 (by /u/Zezombye)");
  534. BufferedReader in = new BufferedReader(
  535. new InputStreamReader(
  536. connection.getInputStream()));
  537.  
  538. StringBuilder response = new StringBuilder();
  539. String inputLine;
  540.  
  541. while ((inputLine = in.readLine()) != null)
  542. response.append(inputLine);
  543.  
  544. in.close();
  545. //toast("Successfully connected");
  546. return response.toString();
  547. }
  548.  
  549. static String modifyText(String str) {
  550. str = str.replaceAll("\\\\\\\"", "&q;"); //transforme \" en "
  551. str = str.replaceAll("\\n", "\n"); //transforme \n en nouvelle ligne
  552. str = str.replaceAll("\\\\\\\\", "\\\\"); // transforme \\ en \
  553. str = str.replaceAll("&amp;", "&");
  554. return str;
  555. }
  556.  
  557. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement