Handle the new "wpEditToken" input parameter for upload
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / actions / mediawiki / post / PostJob.java
1 package net.sourceforge.phpeclipse.wiki.actions.mediawiki.post;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.StringWriter;
6 import java.util.HashMap;
7
8 import net.sourceforge.phpeclipse.wiki.actions.ProblemConsole;
9 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia;
10 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.Content;
11 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.MediaWikiConnector;
12 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.MethodException;
13 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.PageNotEditableException;
14 import net.sourceforge.phpeclipse.wiki.actions.mediawiki.exceptions.UnexpectedAnswerException;
15 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
16 import net.sourceforge.phpeclipse.wiki.internal.Configuration;
17 import net.sourceforge.phpeclipse.wiki.preferences.Util;
18 import net.sourceforge.phpeclipse.wiki.velocity.EditorText;
19 import net.sourceforge.phpeclipse.wiki.xml.Page;
20 import net.sourceforge.phpeclipse.wiki.xml.XStreamManager;
21
22 import org.apache.velocity.VelocityContext;
23 import org.apache.velocity.app.Velocity;
24 import org.eclipse.core.resources.IFile;
25 import org.eclipse.core.resources.ResourcesPlugin;
26 import org.eclipse.core.resources.WorkspaceJob;
27 import org.eclipse.core.runtime.CoreException;
28 import org.eclipse.core.runtime.IPath;
29 import org.eclipse.core.runtime.IProgressMonitor;
30 import org.eclipse.core.runtime.IStatus;
31 import org.eclipse.core.runtime.Path;
32 import org.eclipse.core.runtime.Status;
33 import org.eclipse.core.runtime.jobs.Job;
34 import org.eclipse.ui.progress.IProgressConstants;
35
36 public class PostJob extends WorkspaceJob {
37   IFile[] files;
38
39   IWikipedia wikipedia;
40
41   Configuration configuration;
42
43   String user;
44
45   String password;
46
47   public PostJob(Configuration configuration, IWikipedia wikipedia, String user, String password, IFile[] files) {
48     super("Refresh Job");
49     this.files = files;
50     this.wikipedia = wikipedia;
51     this.user = user;
52     this.password = password;
53     this.configuration = configuration;
54   }
55
56   public String generateUrl(String template, String wikiname) {
57     EditorText text = new EditorText(null);
58     /* first, we init the runtime engine. Defaults are fine. */
59
60     try {
61       Velocity.init();
62
63       /* lets make a Context and put data into it */
64
65       VelocityContext context = new VelocityContext();
66
67       context.put("config", configuration);
68       text.clear();
69       text.setWikiname(wikiname);
70       context.put("text", text);
71
72       /* lets make our own string to render */
73       StringWriter w = new StringWriter();
74       w = new StringWriter();
75       Velocity.evaluate(context, w, "mystring", template);
76       return w.toString();
77
78     } catch (Exception e) {
79       // TODO Auto-generated catch block
80       e.printStackTrace();
81     }
82     return template;
83   }
84
85   private void uploadWiki(String timestamp, String editToken, String body, MediaWikiConnector connector, String actionUrl,
86       String wikiName) throws UnexpectedAnswerException, MethodException, PageNotEditableException, InterruptedException {
87
88     String url = generateUrl(configuration.getURL(), wikiName);
89     //      System.out.println(timestamp);
90     Content content = new Content(timestamp, body);
91
92     connector.store(wikipedia, editToken, actionUrl, wikiName, content, "", false, false);
93
94   }
95
96   public IStatus runInWorkspace(IProgressMonitor monitor) {
97     boolean success = false;
98     IFile file = null;
99     MediaWikiConnector connector = null;
100     InputStream is = null;
101     ProblemConsole console = new ProblemConsole();
102     String actionUrl = configuration.getURL();
103     if (actionUrl == null || actionUrl.equals("")) {
104       // fall back to default settings
105       actionUrl = wikipedia.getActionUrl();
106     }
107     try {
108       if (files.length > 0) {
109         // prefetch for error messages
110         file = files[0];
111       }
112       monitor.beginTask("Upload Wiki Articles: ", 100);
113       int partWork = 100 / files.length;
114       int work = 0;
115       StringBuffer buffer = new StringBuffer();
116       HashMap map = new HashMap();
117       String wikiURLTitle;
118
119       monitor.subTask("Login user:" + user);
120       connector = new MediaWikiConnector();
121       success = connector.login(wikipedia, actionUrl, user, password, false);
122       if (success) {
123         String editToken = connector.loadEditToken(actionUrl, wikipedia.getCharSet(), "plog4u.org bot");
124         if (editToken == null) {
125           console.println("Edit token not found: running in unsave update mode");
126         } else {
127           console.println("Using edit token: " + editToken);
128         }
129         for (int i = 0; i < files.length; i++) {
130           try {
131             file = files[i];
132             is = file.getContents();
133             wikiURLTitle = Util.getURLWikiName(file);
134             String body = StoreWikipediaAction.getInputStreamAsString(is, wikipedia.getCharSet());
135             char ch;
136             boolean noContent = checkNoContent(body);
137             String srcBasePath = Util.getWikiTextsPath(file);
138             String binBasePath = Util.getProjectsWikiOutputPath(file.getProject(), WikiEditorPlugin.HTML_OUTPUT_PATH);
139
140             String fileXMLName = Util.getXMLFileName(file, binBasePath, srcBasePath);
141             IPath path = new Path(fileXMLName);
142             IFile xmlFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
143
144             String timestamp = "";
145             if (xmlFile.exists()) {
146               try {
147                 Page page = XStreamManager.fromXML(xmlFile.getContents());
148                 if (page != null) {
149                   // we've stored information about the article at download time which
150                   // may be more exactly as the standard information
151                   if (!page.isEmpty()) {
152                     // at least one revision exists:
153                     timestamp = page.get(0).getTimestamp();
154                   }
155                   wikiURLTitle = page.getURLTitle();
156                 }
157                 //                timestamp = XMLReader.getDateTimestamp(xmlFile.getContents());
158               } catch (Exception e2) {
159               }
160             }
161
162             if (noContent) {
163               console.println("File: " + file.getLocation().toString() + "\n==>upload not allowed; Wiki text contains no content");
164             } else {
165               monitor.subTask("Upload: " + file.getLocation().toString());
166               uploadWiki(timestamp, editToken, body, connector, actionUrl, wikiURLTitle);
167             }
168
169           } catch (CoreException e1) {
170             if (file != null) {
171               console.println("File: " + file.getLocation().toString() + "\n==>CoreException: " + e1.getMessage());
172             }
173           }
174           if (monitor.isCanceled()) {
175             return Status.CANCEL_STATUS;
176           }
177           work += partWork;
178           monitor.worked(work);
179         }
180       }
181
182       if (isModal(this)) {
183         // The progress dialog is still open show the message
184       } else {
185         setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
186         //            setProperty(IProgressConstants.ACTION_PROPERTY, getWikisCompletedAction());
187       }
188       return Status.OK_STATUS;
189       //        } catch(CoreException e) {
190       //          return e.getStatus();
191     } catch (IOException e) {
192       if (file != null) {
193         console.println("File: " + file.getLocation().toString());
194       }
195       console.println("==>IOException: " + e.getMessage());
196     } catch (UnexpectedAnswerException e) {
197       console.println("==>UnexpectedAnswerException: " + e.getMessage());
198     } catch (InterruptedException e) {
199       if (file != null) {
200         console.println("File: " + file.getLocation().toString());
201       }
202       console.println("==>InterruptedException: " + e.getMessage());
203     } catch (PageNotEditableException e) {
204       if (file != null) {
205         console.println("File: " + file.getLocation().toString());
206       }
207       console.println("==>PageNotEditableException: " + e.getMessage());
208     } catch (MethodException e) {
209       if (file != null) {
210         console.println("File: " + file.getLocation().toString());
211       }
212       console.println("==>HTTP-MethodException: " + e.getMessage());
213     } finally {
214       monitor.done();
215       if (success && connector != null) {
216         try {
217           monitor.subTask("Logout!");
218           connector.logout(wikipedia, actionUrl);
219         } catch (UnexpectedAnswerException e1) {
220           console.println("==>UnexpectedAnswerException: " + e1.getMessage());
221         } catch (MethodException e1) {
222           console.println("==>HTTP-MethodException: " + e1.getMessage());
223         }
224       }
225       if (is != null) {
226         try {
227           is.close();
228         } catch (IOException e1) {
229         }
230       }
231     }
232     if (isModal(this)) {
233       // The progress dialog is still open show the message
234     }
235     return Status.CANCEL_STATUS;
236   }
237
238   /**
239    * @param body
240    * @param j
241    * @return
242    */
243   private boolean checkNoContent(String body) {
244     char ch;
245     boolean noContent = true;
246     int j = 0;
247     try {
248       while (true) {
249         ch = body.charAt(j++);
250         if (!Character.isWhitespace(ch)) {
251           if (ch == '<' && body.charAt(j) == '!' && body.charAt(j + 1) == '-' && body.charAt(j + 2) == '-') {
252             //<!-- ... -->
253             j += 3;
254             while (true) {
255               ch = body.charAt(j++);
256               if (ch == '-' && body.charAt(j) == '-' && body.charAt(j + 1) == '>') {
257                 j += 2;
258                 break;
259               }
260             }
261           } else if (ch == '<' && body.charAt(j) == 'b' && body.charAt(j + 1) == 'r' && body.charAt(j + 2) == '>') {
262             // <br>
263           } else {
264             noContent = false;
265             break;
266           }
267         }
268       }
269     } catch (IndexOutOfBoundsException e) {
270
271     }
272     return noContent;
273   }
274
275   public boolean isModal(Job job) {
276     Boolean isModal = (Boolean) job.getProperty(IProgressConstants.PROPERTY_IN_DIALOG);
277     if (isModal == null) {
278       return false;
279     }
280     return isModal.booleanValue();
281   }
282
283 }