├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── lib
└── utils.js
├── opml
├── dashboard.opml
├── queue.opml
├── river4.opml
├── river4homepage.opml
├── riverbuilder.opml
├── s3.opml
└── utils.opml
├── package.json
└── river4.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | */logs
4 | *.log
5 |
6 | # Runtime data
7 | pids
8 | *.pid
9 | *.seed
10 |
11 | # Directory for instrumented libs generated by jscoverage/JSCover
12 | lib-cov
13 |
14 | # Coverage directory used by tools like istanbul
15 | coverage
16 |
17 | # Unit test xml files
18 | testresults
19 |
20 | # Documentation
21 | doc
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Compiled binary addons (http://nodejs.org/api/addons.html)
27 | build/Release
28 |
29 | # Dependency directory
30 | node_modules
31 |
32 | # Users Environment Variables
33 | .lock-wscript
34 |
35 | ./idea
36 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:0.12-onbuild
2 | EXPOSE 1337
3 | ENV fspath /var/river4/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #### River4
2 |
3 | River4 is a JavaScript river-of-news aggregator running in Node.js
4 |
5 | Important: River5 has been released. It's simpler to set up and runs faster.
6 |
7 | #### How to install
8 |
9 | Here are the instructions for setting up River4 on a system running Node.js, using the local file system for storage.
10 |
11 | #### Links
12 |
13 | 1. Welcome to River4.
14 |
15 | 1. What is a River of News aggregator?
16 |
17 | 2. Why every news organization should have a river.
18 |
19 | 6. The River4 support mail list.
20 |
21 | 7. How to ask for help with software.
22 |
23 | 9. The Hello World of Rivers.
24 |
25 | 10. Editing subscription lists.
26 |
27 | 11. Installing River4 on Ubuntu.
28 |
29 | #### Updates
30 |
31 | ##### v0.120 -- 8/21/15 by DW
32 |
33 | Watch for a change to the mod date of the river4.js file. Quit if it changes. But only if the feature is enabled via config.flWatchAppDateChange boolean.
34 |
35 | If you changed the name of the River4 app, you can provide the new name in config.fnameApp.
36 |
37 | Here's an example of a config.json for this setup.
38 |
39 | ##### v0.118 -- 8/13/15 by DW
40 |
41 | Now handles feeds whose address begins with feed://. We just translate it to http://. Previously there would be an error reading the feed.
42 |
43 | Also created a module, utils.js, instead of including the source in the main body of river.js. River4 was the first Node app I shipped, I've since learned how to modularize Node apps.
44 |
45 | ##### v0.117 -- 7/20/15 by DW
46 |
47 | Lots of small changes to make River4 easier to setup for newbies. ;-)
48 |
49 | 1. If you haven't set any path variables, or set up config.json, River4 will run with the data stored in a river4data sub-folder of the folder containing river4.js, which it automatically creates.
50 |
51 | 2. We don't announce each step of the startup process on the console.
52 |
53 | 3. If there's an ENOENT error reading prefsAndStats.json, we don't report an error, since River4 automatically creates the file the first time it runs. This confused some users, unnecessarily.
54 |
55 | 4. We create the lists folder automatically.
56 |
57 | 5. We no longer install an index.html file in the river4data folder. The file we installed didn't actually work, and it's no longer necessary since the home page of the server is now a perfectly good way to browse the rivers on the server.
58 |
59 | 5. Re-wrote the howto for setup, eliminating two complicated and potentially error-prone steps. The old howto is still there but with a bold statement at the top saying you should use the new one.
60 |
61 | 6. There's a 15-minute video that shows how to set up a River4 installation.
62 |
63 | ##### v0.116 -- 7/4/15 by DW
64 |
65 | The home page of the River4 server now shows you the rivers being maintained by the server. There's a menu that links to the dashboard, the blog, mail list, and GitHub repo.
66 |
67 | ##### v0.115 -- 6/21/15 by DW
68 |
69 | New feature: Callback scripts that run when River4 adds an item to the river.
70 |
71 | ##### v0.114 -- 6/16/15 by DW
72 |
73 | Fixed JSON encoding problem reported by Andrew Shell.
74 |
75 | ##### v0.113 -- 6/7/15 by DW
76 |
77 | We now record the current time in each item in the calendar structure. This is used when building a river to set the whenLastUpdate field.
78 |
79 | ##### v0.112 -- 6/5/15 by DW
80 |
81 | Now when we receive a message saying that a feed updated, we read the feed and rebuild all rivers that it's part of. I wanted to test the framework before going this step.
82 |
83 | Again, a careful code review and testing by others would be appreciated.
84 |
85 | ##### v0.111 -- 6/4/15 by DW
86 |
87 | Added support for rssCloud. Now if a feed has a <cloud> element, we contact the server and go through the subscription protocol. If it all works, we'll be notified of updates to the feed before we poll.
88 |
89 | The rssCloud support is largely untested. However I have upgraded all my copies of River4 to run the new version, and it seems to be functioning well. Code review of the new functionality would be much appreciated.
90 |
91 | We also remove items from each feed's history array when the item no longer appears in the feed. This reduces the size of some of the files in the data folder, in general making the software more efficient.
92 |
93 | Fixed an error that would cause River4 to crash when there were no OPML subscription list files in the lists folder.
94 |
95 | ##### v0.110 -- 5/10/15 by DW
96 |
97 | A new way to configure River4, using a config.son file in the same directory as river4.js.
98 |
99 | ##### v0.109 -- 4/21/15 by DW
100 |
101 | Fixed a bug that would cause generated rivers to be empty immediately after date rollover.
102 |
103 | The fix was to write out an empty array in the calendar structure when the date rollover occurs. The problem was that until there was a new item saved for the day, the first read of the calendar, when building a river would fail, causing the build to finish.
104 |
105 | The problem was discovered in podcatch.com, and written up on the River4 blog.
106 |
107 | ##### v0.108 -- 12/5/14 by DW
108 |
109 | There's now a River4 Console app, at http://river4.io/ that allows you to edit subscription lists in an outliner, and set some of the server preferences remotely. It's documented on the River4 blog.
110 |
111 | ##### v0.100 -- 11/2/14 by DW
112 |
113 | Fixed a bug in file name processing.
114 |
115 | ##### v0.99 -- 11/1/14 by DW
116 |
117 | Two fixes for local file system use. 1. Only read lists whose names end with .opml -- there were invisible files on the Mac that would cause problems. 2. When running on Windows and writing to the local file system, there are more illegal characters. Replace them with underscores.
118 |
119 | ##### v0.97 -- 10/16/14 by DW
120 |
121 | Apparently there was a change in format in the FeedParser module, in the way it represents <source:outline> elements. This release handles the change in format so outlines now pass through in a way that's understandable to the RiverBrowser software.
122 |
123 | ##### v0.96 -- 9/24/14 by DW
124 |
125 | This version can be configured to store its data in the local filesystem instead of S3. See the blog post for details.
126 |
127 | ##### v0.95 -- 9/11/14 by DW
128 |
129 | New /ping endpoint, available to be called by a publisher, on behalf of a user, to indicate that a feed has updated, and should be read immediately. Radio3 has this facility as of today, as does Fargo.
130 |
131 | ##### v0.94 -- 8/6/14 by DW
132 |
133 | Fixed a problem that caused rivers to display only old stories. Full explanation on the blog.
134 |
135 | ##### v0.93 -- 7/31/14 by DW
136 |
137 | Added more fields to the struct the /status call returns. It now says what the s3path is, what port the server is running on, and if you've defined a s3defaultAcl (see v0.91) what the value of that parameter is.
138 |
139 | ##### v0.91 -- 7/19/14 by DW
140 |
141 | A new environment variable, s3defaultAcl, if present specifies the permissions on S3 files we create. The default is public-read. With this parameter, it may be possible to run a private installation of River4.
142 |
143 | ##### v0.90 -- 7/19/14 by DW
144 |
145 | New <source:outline> elements flow through River4. See the docs for the source namespace for details.
146 |
147 | ##### v0.89 -- 6/19/14 by DW
148 |
149 | One small change to package.json, and no changes to the JavaScript code.
150 |
151 | ##### v0.88 -- 6/17/14 by DW
152 |
153 | A subscription list can now contain an include node, so you can have a list of lists. Full explanation in this blog post.
154 |
155 | Changed the package.json file to require Node v0.8.x. Previously it was 0.6.x. This should make it possible to deploy on Nodejitsu without modification, per Dave Seidel's report.
156 |
157 | ##### v0.87 -- 6/09/14 by DW
158 |
159 | Fixed a bug that would cause River4 to crash when processing an item with a null title.
160 |
161 | ##### v0.86 -- 6/09/14 by DW
162 |
163 | Fixed a bug that would cause River4 to crash when reading an item from a subscription list that didn't have an xmlUrl attribute.
164 |
165 | ##### v0.85 -- 6/07/14 by DW
166 |
167 | Two fixes, explained here.
168 |
169 | ##### v0.84 -- 6/06/14 by DW
170 |
171 | Two fixes, explained here.
172 |
173 | ##### v0.83 -- 6/06/14 by DW
174 |
175 | Now if there's an error in any JSON code we try to parse, we display an error message in the console, along with the path to the S3 file we were trying to read.
176 |
177 | ##### v0.81 -- 6/02/14 by DW
178 |
179 | serverData.stats now has a copy of the last story added to the river. The dashboard page displays it.
180 |
181 | ##### v0.80 -- 6/02/14 by DW
182 |
183 | New "dashboard" feature. If your server is running at aggregator.mydomain.com, if you go to:
184 |
185 | http://aggregator.mydomain.com/dashboard
186 |
187 | You'll get a real-time readout of what your aggregator is doing.
188 |
189 | The HTML source for the dashboard page is in dashboard.opml in the opml folder in the repository.
190 |
191 | #### Docker
192 |
193 | There is an experimental Docker installer. Notes about using it are on the wiki.
194 |
195 | #### Amazon S3, Heroku
196 |
197 | When we started developing River4, we were targeting Heroku, because it was so easy and inexpensive to start with. They have since changed their pricing, so it's not as attractive, so we're now recommending the filesystem configuration, above.
198 |
199 | 1. The howto with instructions for installing River4 using Amazon S3 for storage.
200 |
201 | 3. Heroku How To -- get a Heroku server running with Fargo Publisher, the back-end for Fargo.
202 |
203 | 4. Bare-bones Heroku do -- checklist for setting up a Heroku server running Node.js from a Mac desktop.
204 |
205 | #### Thanks!
206 |
207 | Thanks to two developer friends, Dan MacTough and Eric Kidd, who helped this Node.js newbie get this app up and running.
208 |
209 | Specifically thanks to Dan for writing the excellent feedparser and opmlparser packages that are incorporated in River4.
210 |
211 | #### Notes
212 |
213 | 1. I edit code in an outliner, which is then turned into JavaScript. The "opml" folder in the repository contains the versions of the code that I edit. The comments are stripped out of the code before it's converted to raw JS, so there is information for developers in the OPML that isn't in the main files (though all the running code is in both).
214 |
215 | 2. The first released version is 0.79. They will increment by one one-hundredth every release. At some point I'll call it 1.0, then subsequent releases will be 1.01, 1.02 etc.
216 |
217 | #### Questions, comments?
218 |
219 | Please post a note on the River4 mail list.
220 |
221 |
--------------------------------------------------------------------------------
/lib/utils.js:
--------------------------------------------------------------------------------
1 | exports.beginsWith = beginsWith;
2 | exports.endsWith = endsWith;
3 | exports.stringCountFields = stringCountFields;
4 | exports.stringDelete = stringDelete;
5 | exports.stringMid = stringMid;
6 | exports.padWithZeros = padWithZeros;
7 | exports.getDatePath = getDatePath;
8 | exports.secondsSince = secondsSince;
9 | exports.bumpUrlString = bumpUrlString;
10 | exports.stringContains = stringContains;
11 | exports.sameDay = sameDay;
12 | exports.jsonStringify = jsonStringify;
13 | exports.stringNthField = stringNthField;
14 | exports.getBoolean = getBoolean;
15 | exports.isAlpha = isAlpha;
16 | exports.isNumeric = isNumeric;
17 | exports.stringLastField = stringLastField;
18 | exports.multipleReplaceAll = multipleReplaceAll;
19 | exports.replaceAll = replaceAll; //2/17/15 by DW
20 | exports.kilobyteString = kilobyteString;
21 | exports.megabyteString = megabyteString;
22 | exports.gigabyteString = gigabyteString;
23 | exports.stringLower = stringLower;
24 | exports.filledString = filledString;
25 | exports.innerCaseName = innerCaseName;
26 | exports.copyScalars = copyScalars;
27 | exports.stripMarkup = stripMarkup;
28 | exports.hotUpText = hotUpText;
29 | exports.sleepTillTopOfMinute = sleepTillTopOfMinute;
30 | exports.random = random;
31 | exports.stringPopLastField = stringPopLastField;
32 | exports.trimWhitespace = trimWhitespace;
33 | exports.dateYesterday = dateYesterday;
34 | exports.maxStringLength = maxStringLength;
35 |
36 | function sameDay (d1, d2) {
37 | //returns true if the two dates are on the same day
38 | d1 = new Date (d1);
39 | d2 = new Date (d2);
40 | return ((d1.getFullYear () == d2.getFullYear ()) && (d1.getMonth () == d2.getMonth ()) && (d1.getDate () == d2.getDate ()));
41 | }
42 | function dayGreaterThanOrEqual (d1, d2) { //9/2/14 by DW
43 | d1 = new Date (d1);
44 | d1.setHours (0);
45 | d1.setMinutes (0);
46 | d1.setSeconds (0);
47 |
48 | d2 = new Date (d2);
49 | d2.setHours (0);
50 | d2.setMinutes (0);
51 | d2.setSeconds (0);
52 |
53 | return (d1 >= d2);
54 | }
55 | function stringLower (s) {
56 | if (s === undefined) { //1/26/15 by DW
57 | return ("");
58 | }
59 | s = s.toString (); //1/26/15 by DW
60 | return (s.toLowerCase ());
61 | }
62 | function secondsSince (when) {
63 | var now = new Date ();
64 | when = new Date (when);
65 | return ((now - when) / 1000);
66 | }
67 | function padWithZeros (num, ctplaces) {
68 | var s = num.toString ();
69 | while (s.length < ctplaces) {
70 | s = "0" + s;
71 | }
72 | return (s);
73 | }
74 | function getDatePath (theDate, flLastSeparator) {
75 | if (theDate === undefined) {
76 | theDate = new Date ();
77 | }
78 | else {
79 | theDate = new Date (theDate); //8/12/14 by DW -- make sure it's a date type
80 | }
81 | if (flLastSeparator === undefined) {
82 | flLastSeparator = true;
83 | }
84 |
85 | var month = padWithZeros (theDate.getMonth () + 1, 2);
86 | var day = padWithZeros (theDate.getDate (), 2);
87 | var year = theDate.getFullYear ();
88 |
89 | if (flLastSeparator) {
90 | return (year + "/" + month + "/" + day + "/");
91 | }
92 | else {
93 | return (year + "/" + month + "/" + day);
94 | }
95 | }
96 | function multipleReplaceAll (s, adrTable, flCaseSensitive, startCharacters, endCharacters) {
97 | if(flCaseSensitive===undefined){
98 | flCaseSensitive = false;
99 | }
100 | if(startCharacters===undefined){
101 | startCharacters="";
102 | }
103 | if(endCharacters===undefined){
104 | endCharacters="";
105 | }
106 | for( var item in adrTable){
107 | var replacementValue = adrTable[item];
108 | var regularExpressionModifier = "g";
109 | if(!flCaseSensitive){
110 | regularExpressionModifier = "gi";
111 | }
112 | var regularExpressionString = (startCharacters+item+endCharacters).replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
113 | var regularExpression = new RegExp(regularExpressionString, regularExpressionModifier);
114 | s = s.replace(regularExpression, replacementValue);
115 | }
116 | return s;
117 | }
118 | function endsWith (s, possibleEnding, flUnicase) {
119 | if ((s === undefined) || (s.length == 0)) {
120 | return (false);
121 | }
122 | var ixstring = s.length - 1;
123 | if (flUnicase === undefined) {
124 | flUnicase = true;
125 | }
126 | if (flUnicase) {
127 | for (var i = possibleEnding.length - 1; i >= 0; i--) {
128 | if (stringLower (s [ixstring--]) != stringLower (possibleEnding [i])) {
129 | return (false);
130 | }
131 | }
132 | }
133 | else {
134 | for (var i = possibleEnding.length - 1; i >= 0; i--) {
135 | if (s [ixstring--] != possibleEnding [i]) {
136 | return (false);
137 | }
138 | }
139 | }
140 | return (true);
141 | }
142 | function stringContains (s, whatItMightContain, flUnicase) { //11/9/14 by DW
143 | if (flUnicase === undefined) {
144 | flUnicase = true;
145 | }
146 | if (flUnicase) {
147 | s = s.toLowerCase ();
148 | whatItMightContain = whatItMightContain.toLowerCase ();
149 | }
150 | return (s.indexOf (whatItMightContain) != -1);
151 | }
152 | function beginsWith (s, possibleBeginning, flUnicase) {
153 | if (s === undefined) { //7/15/15 by DW
154 | return (false);
155 | }
156 | if (s.length == 0) { //1/1/14 by DW
157 | return (false);
158 | }
159 | if (flUnicase === undefined) {
160 | flUnicase = true;
161 | }
162 | if (flUnicase) {
163 | for (var i = 0; i < possibleBeginning.length; i++) {
164 | if (stringLower (s [i]) != stringLower (possibleBeginning [i])) {
165 | return (false);
166 | }
167 | }
168 | }
169 | else {
170 | for (var i = 0; i < possibleBeginning.length; i++) {
171 | if (s [i] != possibleBeginning [i]) {
172 | return (false);
173 | }
174 | }
175 | }
176 | return (true);
177 | }
178 | function isAlpha (ch) {
179 | return (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')));
180 | }
181 | function isNumeric (ch) {
182 | return ((ch >= '0') && (ch <= '9'));
183 | }
184 | function trimLeading (s, ch) {
185 | while (s.charAt (0) === ch) {
186 | s = s.substr (1);
187 | }
188 | return (s);
189 | }
190 | function trimTrailing (s, ch) {
191 | while (s.charAt (s.length - 1) === ch) {
192 | s = s.substr (0, s.length - 1);
193 | }
194 | return (s);
195 | }
196 | function trimWhitespace (s) { //rewrite -- 5/30/14 by DW
197 | function isWhite (ch) {
198 | switch (ch) {
199 | case " ": case "\r": case "\n": case "\t":
200 | return (true);
201 | }
202 | return (false);
203 | }
204 | if (s === undefined) { //9/10/14 by DW
205 | return ("");
206 | }
207 | while (isWhite (s.charAt (0))) {
208 | s = s.substr (1);
209 | }
210 | while (s.length > 0) {
211 | if (!isWhite (s.charAt (0))) {
212 | break;
213 | }
214 | s = s.substr (1);
215 | }
216 | while (s.length > 0) {
217 | if (!isWhite (s.charAt (s.length - 1))) {
218 | break;
219 | }
220 | s = s.substr (0, s.length - 1);
221 | }
222 | return (s);
223 | }
224 | function addPeriodAtEnd (s) {
225 | s = trimWhitespace (s);
226 | if (s.length == 0) {
227 | return (s);
228 | }
229 | switch (s [s.length - 1]) {
230 | case ".":
231 | case ",":
232 | case "?":
233 | case "\"":
234 | case "'":
235 | case ":":
236 | case ";":
237 | case "!":
238 | return (s);
239 | default:
240 | return (s + ".");
241 | }
242 | }
243 | function getBoolean (val) { //12/5/13 by DW
244 | switch (typeof (val)) {
245 | case "string":
246 | if (val.toLowerCase () == "true") {
247 | return (true);
248 | }
249 | break;
250 | case "boolean":
251 | return (val);
252 | case "number":
253 | if (val == 1) {
254 | return (true);
255 | }
256 | break;
257 | }
258 | return (false);
259 | }
260 | function bumpUrlString (s) { //5/10/14 by DW
261 | if (s === undefined) {
262 | s = "0";
263 | }
264 | function bumpChar (ch) {
265 | function num (ch) {
266 | return (ch.charCodeAt (0));
267 | }
268 | if ((ch >= "0") && (ch <= "8")) {
269 | ch = String.fromCharCode (num (ch) + 1);
270 | }
271 | else {
272 | if (ch == "9") {
273 | ch = "a";
274 | }
275 | else {
276 | if ((ch >= "a") && (ch <= "y")) {
277 | ch = String.fromCharCode (num (ch) + 1);
278 | }
279 | else {
280 | throw "rollover!";
281 | }
282 | }
283 | }
284 | return (ch);
285 | }
286 | try {
287 | var chlast = bumpChar (s [s.length - 1]);
288 | s = s.substr (0, s.length - 1) + chlast;
289 | return (s);
290 | }
291 | catch (tryError) {
292 | if (s.length == 1) {
293 | return ("00");
294 | }
295 | else {
296 | s = s.substr (0, s.length - 1);
297 | s = bumpUrlString (s) + "0";
298 | return (s);
299 | }
300 | }
301 | }
302 | function stringDelete (s, ix, ct) {
303 | var start = ix - 1;
304 | var end = (ix + ct) - 1;
305 | var s1 = s.substr (0, start);
306 | var s2 = s.substr (end);
307 | return (s1 + s2);
308 | }
309 | function replaceAll (s, searchfor, replacewith) {
310 | function escapeRegExp (string) {
311 | return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
312 | }
313 | return (s.replace (new RegExp (escapeRegExp (searchfor), 'g'), replacewith));
314 | }
315 | function stringCountFields (s, chdelim) {
316 | var ct = 1;
317 | if (s.length == 0) {
318 | return (0);
319 | }
320 | for (var i = 0; i < s.length; i++) {
321 | if (s [i] == chdelim) {
322 | ct++;
323 | }
324 | }
325 | return (ct)
326 | }
327 | function stringNthField (s, chdelim, n) {
328 | var splits = s.split (chdelim);
329 | if (splits.length >= n) {
330 | return splits [n-1];
331 | }
332 | return ("");
333 | }
334 | function dateYesterday (d) {
335 | return (new Date (new Date (d) - (24 * 60 * 60 * 1000)));
336 | }
337 | function stripMarkup (s) { //5/24/14 by DW
338 | if ((s === undefined) || (s == null) || (s.length == 0)) {
339 | return ("");
340 | }
341 | return (s.replace (/(<([^>]+)>)/ig, ""));
342 | }
343 | function maxStringLength (s, len, flWholeWordAtEnd, flAddElipses) {
344 | if (flWholeWordAtEnd === undefined) {
345 | flWholeWordAtEnd = true;
346 | }
347 | if (flAddElipses === undefined) { //6/2/14 by DW
348 | flAddElipses = true;
349 | }
350 | if (s.length > len) {
351 | s = s.substr (0, len);
352 | if (flWholeWordAtEnd) {
353 | while (s.length > 0) {
354 | if (s [s.length - 1] == " ") {
355 | if (flAddElipses) {
356 | s += "...";
357 | }
358 | break;
359 | }
360 | s = s.substr (0, s.length - 1); //pop last char
361 | }
362 | }
363 | }
364 | return (s);
365 | }
366 | function random (lower, upper) {
367 | var range = upper - lower + 1;
368 | return (Math.floor ((Math.random () * range) + lower));
369 | }
370 | function removeMultipleBlanks (s) { //7/30/14 by DW
371 | return (s.toString().replace (/ +/g, " "));
372 | }
373 | function jsonStringify (jstruct, flFixBreakage) { //7/30/14 by DW
374 | //Changes
375 | //6/16/15; 10:43:25 AM by DW
376 | //Andrew Shell reported an issue in the encoding of JSON that's solved by doing character replacement.
377 | //However, this is too big a change to make for all the code that calls this library routine, so we added a boolean flag, flFixBreakage.
378 | //If this proves to be harmless, we'll change the default to true.
379 | //http://river4.smallpict.com/2015/06/16/jsonEncodingIssueSolved.html
380 | if (flFixBreakage === undefined) {
381 | flFixBreakage = false;
382 | }
383 | var s = JSON.stringify (jstruct, undefined, 4);
384 | if (flFixBreakage) {
385 | s = s.replace (/\u2028/g,'\\u2028').replace (/\u2029/g,'\\u2029');
386 | }
387 | return (s);
388 | }
389 | function stringAddCommas (x) { //5/27/14 by DW
390 | return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
391 | }
392 | function readHttpFile (url, callback, timeoutInMilliseconds, headers) { //5/27/14 by DW xxx
393 | if (timeoutInMilliseconds === undefined) {
394 | timeoutInMilliseconds = 30000;
395 | }
396 | var jxhr = $.ajax ({
397 | url: url,
398 | dataType: "text",
399 | headers: headers,
400 | timeout: timeoutInMilliseconds
401 | })
402 | .success (function (data, status) {
403 | callback (data);
404 | })
405 | .error (function (status) {
406 | console.log ("readHttpFile: url == " + url + ", error == " + jsonStringify (status));
407 | callback (undefined);
408 | });
409 | }
410 | function readHttpFileThruProxy (url, type, callback) { //10/25/14 by DW
411 | var urlReadFileApi = "http://pub2.fargo.io:5347/httpReadUrl";
412 | if (type === undefined) {
413 | type = "text/plain";
414 | }
415 | var jxhr = $.ajax ({
416 | url: urlReadFileApi + "?url=" + encodeURIComponent (url) + "&type=" + encodeURIComponent (type),
417 | dataType: "text" ,
418 | timeout: 30000
419 | })
420 | .success (function (data, status) {
421 | if (callback != undefined) {
422 | callback (data);
423 | }
424 | })
425 | .error (function (status) {
426 | console.log ("readHttpFileThruProxy: url == " + url + ", error == " + status.statusText + ".");
427 | if (callback != undefined) {
428 | callback (undefined);
429 | }
430 | });
431 | }
432 | function stringPopLastField (s, chdelim) { //5/28/14 by DW
433 | if (s.length == 0) {
434 | return (s);
435 | }
436 | if (endsWith (s, chdelim)) {
437 | s = stringDelete (s, s.length, 1);
438 | }
439 | while (s.length > 0) {
440 | if (endsWith (s, chdelim)) {
441 | return (stringDelete (s, s.length, 1));
442 | }
443 | s = stringDelete (s, s.length, 1);
444 | }
445 | return (s);
446 | }
447 | function stringPopExtension (s) { //4/29/15 by DW
448 | for (var i = s.length - 1; i >= 0; i--) {
449 | if (s [i] == ".") {
450 | return (stringMid (s, 1, i));
451 | }
452 | }
453 | return (s);
454 | }
455 | function filledString (ch, ct) { //6/4/14 by DW
456 | var s = "";
457 | for (var i = 0; i < ct; i++) {
458 | s += ch;
459 | }
460 | return (s);
461 | }
462 | function encodeXml (s) { //7/15/14 by DW
463 | var charMap = {
464 | '<': '<',
465 | '>': '>',
466 | '&': '&',
467 | '"': '&'+'quot;'
468 | };
469 | s = s.toString();
470 | s = s.replace(/\u00A0/g, " ");
471 | var escaped = s.replace(/[<>&"]/g, function(ch) {
472 | return charMap [ch];
473 | });
474 | return escaped;
475 | }
476 | function decodeXml (s) { //11/7/14 by DW
477 | return (s.replace (/</g,'<').replace(/>/g,'>').replace(/&/g,'&'));
478 | }
479 | function hotUpText (s, url) { //7/18/14 by DW
480 |
481 | if (url === undefined) { //makes it easier to call -- 3/14/14 by DW
482 | return (s);
483 | }
484 |
485 | function linkit (s) {
486 | return ("" + s + "");
487 | }
488 | var ixleft = s.indexOf ("["), ixright = s.indexOf ("]");
489 | if ((ixleft == -1) || (ixright == -1)) {
490 | return (linkit (s));
491 | }
492 | if (ixright < ixleft) {
493 | return (linkit (s));
494 | }
495 |
496 | var linktext = s.substr (ixleft + 1, ixright - ixleft - 1); //string.mid (s, ixleft, ixright - ixleft + 1);
497 | linktext = "" + linktext + "";
498 |
499 | var leftpart = s.substr (0, ixleft);
500 | var rightpart = s.substr (ixright + 1, s.length);
501 | s = leftpart + linktext + rightpart;
502 | return (s);
503 | }
504 | function getDomainFromUrl (url) { //7/11/15 by DW
505 | if ((url != null ) && (url != "")) {
506 | url = url.replace("www.","").replace("www2.", "").replace("feedproxy.", "").replace("feeds.", "");
507 | var root = url.split('?')[0]; // cleans urls of form http://domain.com?a=1&b=2
508 | url = root.split('/')[2];
509 | }
510 | return (url);
511 | };
512 | function getFavicon (url) { //7/18/14 by DW
513 | var domain = getDomainFromUrl (url);
514 | return ("http://www.google.com/s2/favicons?domain=" + domain);
515 | };
516 | function getURLParameter (name) { //7/21/14 by DW
517 | return (decodeURI ((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]));
518 | }
519 | function urlSplitter (url) { //7/15/14 by DW
520 | var pattern = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
521 | var result = pattern.exec (url);
522 | if (result == null) {
523 | result = [];
524 | result [5] = url;
525 | }
526 | var splitUrl = {
527 | scheme: result [1],
528 | host: result [3],
529 | port: result [4],
530 | path: result [5],
531 | query: result [6],
532 | hash: result [7]
533 | };
534 | return (splitUrl);
535 | }
536 | function innerCaseName (text) { //8/12/14 by DW
537 | var s = "", ch, flNextUpper = false;
538 | text = stripMarkup (text);
539 | for (var i = 0; i < text.length; i++) {
540 | ch = text [i];
541 | if (isAlpha (ch) || isNumeric (ch)) {
542 | if (flNextUpper) {
543 | ch = ch.toUpperCase ();
544 | flNextUpper = false;
545 | }
546 | else {
547 | ch = ch.toLowerCase ();
548 | }
549 | s += ch;
550 | }
551 | else {
552 | if (ch == ' ') {
553 | flNextUpper = true;
554 | }
555 | }
556 | }
557 | return (s);
558 | }
559 | function hitCounter (counterGroup, counterServer) { //8/12/14 by DW
560 | var defaultCounterGroup = "scripting", defaultCounterServer = "http://counter2.fargo.io:5337/counter";
561 | var thispageurl = location.href;
562 | if (counterGroup === undefined) {
563 | counterGroup = defaultCounterGroup;
564 | }
565 | if (counterServer === undefined) {
566 | counterServer = defaultCounterServer;
567 | }
568 | if (thispageurl === undefined) {
569 | thispageurl = "";
570 | }
571 | if (endsWith (thispageurl, "#")) {
572 | thispageurl = thispageurl.substr (0, thispageurl.length - 1);
573 | }
574 | var jxhr = $.ajax ({
575 | url: counterServer + "?group=" + encodeURIComponent (counterGroup) + "&referer=" + encodeURIComponent (document.referrer) + "&url=" + encodeURIComponent (thispageurl),
576 | dataType: "jsonp",
577 | jsonpCallback : "getData",
578 | timeout: 30000
579 | })
580 | .success (function (data, status, xhr) {
581 | console.log ("hitCounter: counter ping accepted by server, group == " + counterGroup + ", page url == " + thispageurl);
582 | })
583 | .error (function (status, textStatus, errorThrown) {
584 | console.log ("hitCounter: counter ping error: " + textStatus);
585 | });
586 | }
587 | function stringMid (s, ix, len) { //8/12/14 by DW
588 | return (s.substr (ix-1, len));
589 | }
590 | function getCmdKeyPrefix () { //8/15/14 by DW
591 | if (navigator.platform.toLowerCase ().substr (0, 3) == "mac") {
592 | return ("⌘");
593 | }
594 | else {
595 | return ("Ctrl+");
596 | }
597 | }
598 | function getRandomSnarkySlogan () { //8/15/14 by DW
599 | var snarkySlogans = [
600 | "Good for the environment.",
601 | "All baking done on premises.",
602 | "Still diggin!",
603 | "It's even worse than it appears.",
604 | "Ask not what the Internet can do for you...",
605 | "You should never argue with a crazy man.",
606 | "Welcome back my friends to the show that never ends.",
607 | "Greetings, citizen of Planet Earth. We are your overlords. :-)",
608 | "We don't need no stinkin rock stars.",
609 | "This aggression will not stand.",
610 | "Pay no attention to the man behind the curtain.",
611 | "Only steal from the best.",
612 | "Reallll soooon now...",
613 | "What a long strange trip it's been.",
614 | "Ask not what the Internet can do for you.",
615 | "When in doubt, blog.",
616 | "Shut up and eat your vegetables.",
617 | "Don't slam the door on the way out.",
618 | "Yeah well, that's just, you know, like, your opinion, man.",
619 | "So, it has come to this."
620 | ]
621 | return (snarkySlogans [random (0, snarkySlogans.length - 1)]);
622 | }
623 | function dayOfWeekToString (theDay) { //8/23/14 by DW
624 | var weekday = [
625 | "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
626 | ];
627 | return (weekday[theDay]);
628 | }
629 | function viewDate (when, flShortDayOfWeek) { //8/23/14 by DW
630 | var now = new Date ();
631 | when = new Date (when);
632 | if (sameDay (when, now)) {
633 | return (timeString (when, false)) //2/9/13 by DW;
634 | }
635 | else {
636 | var oneweek = 1000 * 60 * 60 * 24 * 7;
637 | var cutoff = now - oneweek;
638 | if (when > cutoff) { //within the last week
639 | var s = dayOfWeekToString (when.getDay ());
640 | if (flShortDayOfWeek) {
641 | s = s.substring (0, 3);
642 | }
643 | return (s);
644 | }
645 | else {
646 | return (when.toLocaleDateString ());
647 | }
648 | }
649 | }
650 | function timeString (when, flIncludeSeconds) { //8/26/14 by DW
651 | var hour = when.getHours (), minutes = when.getMinutes (), ampm = "AM", s;
652 | if (hour >= 12) {
653 | ampm = "PM";
654 | }
655 | if (hour > 12) {
656 | hour -= 12;
657 | }
658 | if (hour == 0) {
659 | hour = 12;
660 | }
661 | if (minutes < 10) {
662 | minutes = "0" + minutes;
663 | }
664 | if (flIncludeSeconds) {
665 | var seconds = when.getSeconds ();
666 | if (seconds < 10) {
667 | seconds = "0" + seconds;
668 | }
669 | s = hour + ":" + minutes + ":" + seconds + ampm;
670 | }
671 | else {
672 | s = hour + ":" + minutes + ampm;
673 | }
674 | return (s);
675 | }
676 | function stringLastField (s, chdelim) { //8/27/14 by DW
677 | var ct = stringCountFields (s, chdelim);
678 | if (ct == 0) { //8/31/14 by DW
679 | return (s);
680 | }
681 | return (stringNthField (s, chdelim, ct));
682 | }
683 | function maxLengthString (s, maxlength) { //8/27/14 by DW
684 | if (s.length > maxlength) {
685 | s = s.substr (0, maxlength);
686 | while (true) {
687 | var len = s.length; flbreak = false;
688 | if (len == 0) {
689 | break;
690 | }
691 | if (s [len - 1] == " ") {
692 | flbreak = true;
693 | }
694 | s = s.substr (0, len - 1);
695 | if (flbreak) {
696 | break;
697 | }
698 | }
699 | s = s + "...";
700 | }
701 | return (s);
702 | }
703 | function formatDate (theDate, dateformat, timezone) { //8/28/14 by DW
704 | if (theDate === undefined) {
705 | theDate = new Date ();
706 | }
707 | if (dateformat === undefined) {
708 | dateformat = "%c";
709 | }
710 | if (timezone === undefined) {
711 | timezone = - (new Date ().getTimezoneOffset () / 60);
712 | }
713 | try {
714 | var offset = new Number (timezone);
715 | var d = new Date (theDate);
716 | var localTime = d.getTime ();
717 | var localOffset = d.getTimezoneOffset () * 60000;
718 | var utc = localTime + localOffset;
719 | var newTime = utc + (3600000 * offset);
720 | return (new Date (newTime).strftime (dateformat));
721 | }
722 | catch (tryerror) {
723 | return (new Date (theDate).strftime (dateformat));
724 | }
725 | }
726 | function addPeriodToSentence (s) { //8/29/14 by DW
727 | if (s.length > 0) {
728 | var fladd = true;
729 | var ch = s [s.length - 1];
730 | switch (ch) {
731 | case "!": case "?": case ":":
732 | fladd = false;
733 | break;
734 | default:
735 | if (endsWith (s, ".\"")) {
736 | fladd = false;
737 | }
738 | else {
739 | if (endsWith (s, ".'")) {
740 | fladd = false;
741 | }
742 | }
743 | }
744 | if (fladd) {
745 | s += ".";
746 | }
747 | }
748 | return (s);
749 | }
750 | function copyScalars (source, dest) { //8/31/14 by DW
751 | for (var x in source) {
752 | var type, val = source [x];
753 | if (val instanceof Date) {
754 | val = val.toString ();
755 | }
756 | type = typeof (val);
757 | if ((type != "object") && (type != undefined)) {
758 | dest [x] = val;
759 | }
760 | }
761 | }
762 | function linkToDomainFromUrl (url, flshort, maxlength) { //10/10/14 by DW
763 | var splitUrl = urlSplitter (url), host = splitUrl.host.toLowerCase ();
764 | if (flshort === undefined) {
765 | flshort = false;
766 | }
767 | if (flshort) {
768 | var splithost = host.split (".");
769 | if (splithost.length == 3) {
770 | host = splithost [1];
771 | }
772 | else {
773 | host = splithost [0];
774 | }
775 | }
776 | else {
777 | if (beginsWith (host, "www.")) {
778 | host = stringDelete (host, 1, 4);
779 | }
780 | }
781 |
782 | if (maxlength != undefined) { //10/10/14; 10:46:56 PM by DW
783 | if (host.length > maxlength) {
784 | host = stringMid (host, 1, maxlength) + "...";
785 | }
786 | }
787 |
788 | return ("" + host + "");
789 | }
790 | function getRandomPassword (ctchars) { //10/14/14 by DW
791 | var s= "", ch;
792 | while (s.length < ctchars) {
793 | ch = String.fromCharCode (random (33, 122));
794 | if (isAlpha (ch) || isNumeric (ch)) {
795 | s += ch;
796 | }
797 | }
798 | return (s.toLowerCase ());
799 | }
800 | function monthToString (theMonthNum) { //11/4/14 by DW
801 |
802 |
803 | var theDate;
804 | if (theMonthNum === undefined) {
805 | theDate = new Date ();
806 | }
807 | else {
808 | theDate = new Date ((theMonthNum + 1) + "/1/2014");
809 | }
810 | return (formatDate (theDate, "%B"));
811 | }
812 | function getCanonicalName (text) { //11/4/14 by DW
813 | var s = "", ch, flNextUpper = false;
814 | text = stripMarkup (text); //6/30/13 by DW
815 | for (var i = 0; i < text.length; i++) {
816 | ch = text [i];
817 | if (isAlpha (ch) || isNumeric (ch)) {
818 | if (flNextUpper) {
819 | ch = ch.toUpperCase ();
820 | flNextUpper = false;
821 | }
822 | else {
823 | ch = ch.toLowerCase ();
824 | }
825 | s += ch;
826 | }
827 | else {
828 | if (ch == ' ') {
829 | flNextUpper = true;
830 | }
831 | }
832 | }
833 | return (s);
834 | }
835 | function clockNow () { //11/7/14 by DW
836 | return (new Date ());
837 | }
838 | function sleepTillTopOfMinute (callback) { //11/22/14 by DW
839 | var ctseconds = Math.round (60 - (new Date ().getSeconds () + 60) % 60);
840 | if (ctseconds == 0) {
841 | ctseconds = 60;
842 | }
843 | setTimeout (callback, ctseconds * 1000); //8/13/15 by DW -- was hard-coded to "everyMinute" ignored the callback param, fixed
844 | }
845 | function scheduleNextRun (callback, ctMillisecsBetwRuns) { //11/27/14 by DW
846 | var ctmilliseconds = ctMillisecsBetwRuns - (Number (new Date ().getMilliseconds ()) + ctMillisecsBetwRuns) % ctMillisecsBetwRuns;
847 | setTimeout (callback, ctmilliseconds);
848 | }
849 | function urlEncode (s) { //12/4/14 by DW
850 | return (encodeURIComponent (s));
851 | }
852 | function popTweetNameAtStart (s) { //12/8/14 by DW
853 | var ch;
854 | s = trimWhitespace (s);
855 | if (s.length > 0) {
856 | if (s.charAt (0) == "@") {
857 | while (s.charAt (0) != " ") {
858 | s = s.substr (1)
859 | }
860 | while (s.length > 0) {
861 | ch = s.charAt (0);
862 | if ((ch != " ") && (ch != "-")) {
863 | break;
864 | }
865 | s = s.substr (1)
866 | }
867 | }
868 | }
869 | return (s);
870 | }
871 | function httpHeadRequest (url, callback) { //12/17/14 by DW
872 | var jxhr = $.ajax ({
873 | url: url,
874 | type: "HEAD",
875 | dataType: "text",
876 | timeout: 30000
877 | })
878 | .success (function (data, status, xhr) {
879 | callback (xhr); //you can do xhr.getResponseHeader to get one of the header elements
880 | })
881 | }
882 | function httpExt2MIME (ext) { //12/24/14 by DW
883 | var lowerext = stringLower (ext);
884 | var map = {
885 | "au": "audio/basic",
886 | "avi": "application/x-msvideo",
887 | "bin": "application/x-macbinary",
888 | "css": "text/css",
889 | "dcr": "application/x-director",
890 | "dir": "application/x-director",
891 | "dll": "application/octet-stream",
892 | "doc": "application/msword",
893 | "dtd": "text/dtd",
894 | "dxr": "application/x-director",
895 | "exe": "application/octet-stream",
896 | "fatp": "text/html",
897 | "ftsc": "text/html",
898 | "fttb": "text/html",
899 | "gif": "image/gif",
900 | "gz": "application/x-gzip",
901 | "hqx": "application/mac-binhex40",
902 | "htm": "text/html",
903 | "html": "text/html",
904 | "jpeg": "image/jpeg",
905 | "jpg": "image/jpeg",
906 | "js": "application/javascript",
907 | "mid": "audio/x-midi",
908 | "midi": "audio/x-midi",
909 | "mov": "video/quicktime",
910 | "mp3": "audio/mpeg",
911 | "pdf": "application/pdf",
912 | "png": "image/png",
913 | "ppt": "application/mspowerpoint",
914 | "ps": "application/postscript",
915 | "ra": "audio/x-pn-realaudio",
916 | "ram": "audio/x-pn-realaudio",
917 | "sit": "application/x-stuffit",
918 | "sys": "application/octet-stream",
919 | "tar": "application/x-tar",
920 | "text": "text/plain",
921 | "txt": "text/plain",
922 | "wav": "audio/x-wav",
923 | "wrl": "x-world/x-vrml",
924 | "xml": "text/xml",
925 | "zip": "application/zip"
926 | };
927 | for (x in map) {
928 | if (stringLower (x) == lowerext) {
929 | return (map [x]);
930 | }
931 | }
932 | return ("text/plain");
933 | }
934 | function kilobyteString (num) { //1/24/15 by DW
935 | num = Number (num) / 1024;
936 | return (num.toFixed (2) + "K");
937 | }
938 | function megabyteString (num) { //1/24/15 by DW
939 | var onemeg = 1024 * 1024;
940 | if (num <= onemeg) {
941 | return (kilobyteString (num));
942 | }
943 | num = Number (num) / onemeg;
944 | return (num.toFixed (2) + "MB");
945 | }
946 | function gigabyteString (num) { //1/24/15 by DW
947 | var onegig = 1024 * 1024 * 1024;
948 | if (num <= onegig) {
949 | return (megabyteString (num));
950 | }
951 | num = Number (num) / onegig;
952 | return (num.toFixed (2) + "GB");
953 | }
954 | function dateToNumber (theDate) { //2/15/15 by DW
955 | return (Number (new Date (theDate)));
956 | }
957 | function getFileModDate (f, callback) { //8/26/15 by DW
958 | fs.exists (f, function (flExists) {
959 | if (flExists) {
960 | fs.stat (f, function (err, stats) {
961 | if (err) {
962 | callback (undefined);
963 | }
964 | else {
965 | callback (new Date (stats.mtime).toString ());
966 | }
967 | });
968 | }
969 | else {
970 | callback (undefined);
971 | }
972 | });
973 | }
974 |
975 |
--------------------------------------------------------------------------------
/opml/dashboard.opml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | dashboard.html
6 | <%dateModified%>
7 |
8 | 1
9 | 300
10 | 700
11 | 900
12 | 1500
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 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
--------------------------------------------------------------------------------
/opml/queue.opml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | queue.js
6 |
7 | 1
8 | 300
9 | 700
10 | 900
11 | 1500
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 |
--------------------------------------------------------------------------------
/opml/river4homepage.opml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | river4homepage.html
6 | <%dateModified%>
7 |
8 | 1
9 | 300
10 | 700
11 | 900
12 | 1500
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 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
--------------------------------------------------------------------------------
/opml/riverbuilder.opml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | riverbuilder.js
6 | <%dateModified%>
7 |
8 | 1
9 | 300
10 | 700
11 | 900
12 | 1500
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 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
--------------------------------------------------------------------------------
/opml/s3.opml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | s3.js
6 |
7 | 1
8 | 300
9 | 700
10 | 900
11 | 1500
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 |
208 |
209 |
210 |
211 |
212 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "river4",
3 | "subdomain": "river4",
4 | "description": "River of news aggregator that runs from Amazon S3.",
5 | "author": "Dave Winer ",
6 | "version": "0.0.79",
7 | "scripts": {
8 | "start": "node river4.js"
9 | },
10 | "dependencies" : {
11 | "aws-sdk": "*",
12 | "request": "*",
13 | "MD5": "*",
14 | "feedparser": "*",
15 | "opmlparser": "*"
16 | },
17 | "license": "GPL",
18 | "engines": {
19 | "node": ">=0.8.x"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/river4.js:
--------------------------------------------------------------------------------
1 | var myVersion = "0.122a", myProductName = "River4";
2 |
3 | /* The MIT License (MIT)
4 | Copyright (c) 2014-2015 Dave Winer
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 | SOFTWARE.
23 |
24 | structured listing: http://scripting.com/listings/river4.html
25 | */
26 |
27 | var http = require ("http");
28 | var https = require ("https");
29 | var AWS = require ("aws-sdk");
30 | var s3 = new AWS.S3 ();
31 | var md5 = require ("MD5");
32 | var OpmlParser = require ("opmlparser");
33 | var FeedParser = require ("feedparser");
34 | var request = require ("request");
35 | var urlpack = require ("url");
36 | var util = require ("util");
37 | var fs = require ("fs");
38 | var qs = require ("querystring");
39 | var utils = require ("./lib/utils.js"); //8/13/15 by DW
40 |
41 | var fspath = process.env.fspath; //9/24/14 by DW
42 | var remotePassword = process.env.password; //12/4/14 by DW
43 | var flWatchAppDateChange = false, fnameApp = "river4.js", origAppModDate; //8/21/15 by DW -- can only be sent through config.json
44 |
45 | var s3path = process.env.s3path;
46 | var s3UserListsPath;
47 | var s3UserRiversPath;
48 | var s3PrefsAndStatsPath;
49 | var s3LocalStoragePath; //6/22/15 by DW
50 | var s3FeedsArrayPath;
51 | var s3RiversArrayPath;
52 | var s3FeedsInListsPath;
53 | var s3FeedsDataFolder;
54 | var s3CalendarDataFolder;
55 | var s3ListsDataFolder;
56 | var s3BackupsFolder; //12/4/14 by DW
57 | var s3IndexFile;
58 |
59 | var myPort = Number (process.env.PORT || 1337);
60 |
61 | var urlIndexSource = "http://fargo.io/code/river4/river4homepage.html";
62 | var urlDashboardSource = "http://fargo.io/code/river4/dashboard.html";
63 | var urlServerHomePageSource = "http://fargo.io/code/river4/serverhomepage.html"; //what you get when you go to / on the server
64 | var urlFavicon = "http://fargo.io/favicon.ico"; //7/19/15 by DW
65 |
66 | var whenServerStart = new Date ();
67 | var ct = 0, secsLastInit = 0;
68 |
69 | var serverData = {
70 | prefs: {
71 | enabled: true,
72 | ctMinutesBetwBuilds: 15,
73 | maxConsecutiveFeedErrors: 100,
74 | maxThreads: 10,
75 | ctReadsPerSecond: 2,
76 | maxRiverItems: 100,
77 | maxBodyLength: 280,
78 | flSkipDuplicateTitles: true,
79 | flWriteItemsToFiles: false, //debugging -- 5/30/14 by DW
80 | flRequestCloudNotify: true //6/4/15 by DW
81 | },
82 | stats: {
83 | aggregator: "",
84 | ctHoursServerUp: 0,
85 | ctFeedReads: 0,
86 | ctFeedsReadThisScan: 0,
87 | ctFeedReadsLastHour: 0,
88 | ctFeedReadsThisRun: 0,
89 | ctReadsSkipped: 0,
90 | lastFeedRead: "",
91 | whenLastFeedRead: new Date (0),
92 | secsSinceLastFeedRead: 0,
93 | serialnum: 0, //each new story gets a number
94 | ctStoriesAdded: 0,
95 | ctStoriesAddedThisRun: 0,
96 | whenLastStoryAdded: new Date (0),
97 | ctHits: 0, ctHitsToday: 0, ctHitsThisRun: 0,
98 | ctMinutes: 0,
99 | ctScans: 0,
100 | whenLastScanBegin: new Date (0),
101 | whenLastScanEnd: new Date (0),
102 | flScanningNow: false,
103 | ctRiverSaves: 0,
104 | whenLastRiverSave: new Date (0),
105 | ctRiverSaveErrors: 0,
106 | whenLastRiverSaveError: new Date (0),
107 | ctActiveThreads: 0,
108 | ctHttpSockets: 0,
109 | whenLastBuild: new Date (),
110 | ctListFolderReads: 0,
111 | whenLastListFolderRead: new Date (0),
112 | listNames: new Array (),
113 | ctRiverJsonSaves: 0,
114 | whenLastRiverJsonSave: new Date (0),
115 | ctListSaves: 0,
116 | whenLastListSave: new Date (0),
117 | backupSerialnum: 0,
118 | ctRssCloudUpdates: 0,
119 | whenLastRssCloudUpdate: new Date (0),
120 | ctLocalStorageWrites: 0,
121 | whenLastLocalStorageWrite: new Date (0)
122 | },
123 | flags: []
124 | }
125 | var flHaveServerData = false;
126 |
127 | var feedsArray = [], flFeedsArrayDirty = false;
128 |
129 | var feedsInLists = {}, flFeedsInListsDirty = false; //5/30/14 by DW
130 |
131 | var todaysRiver = [], dayRiverCovers = new Date (), flRiverDirty = false;
132 |
133 | var whenLastEveryMinute = new Date ();
134 | var whenLastRiversBuild = new Date (); //8/6/14 by DW
135 |
136 | var fnameConfig = "config.json"; //5/9/15 by DW
137 | var appConfig; //6/4/15 by DW -- the contents of config.json available to all code
138 |
139 | var addToRiverCallbacksFolder = "callbacks/addToRiver/"; //6/19/15 by DW
140 | var flScheduledEveryMinute = false; //8/22/15 by DW
141 |
142 |
143 |
144 |
145 |
146 | var s3defaultType = "text/plain";
147 | var s3defaultAcl = "public-read";
148 |
149 | var s3stats = {
150 | ctReads: 0, ctBytesRead: 0, ctReadErrors: 0,
151 | ctWrites: 0, ctBytesWritten: 0, ctWriteErrors: 0
152 | };
153 |
154 | function s3SplitPath (path) { //split path like this: /tmp.scripting.com/testing/one.txt -- into bucketname and path.
155 | var bucketname = "";
156 | if (path.length > 0) {
157 | if (path [0] == "/") { //delete the slash
158 | path = path.substr (1);
159 | }
160 | var ix = path.indexOf ("/");
161 | bucketname = path.substr (0, ix);
162 | path = path.substr (ix + 1);
163 | }
164 | return ({Bucket: bucketname, Key: path});
165 | }
166 | function s3NewObject (path, data, type, acl, callback, metadata) {
167 | var splitpath = s3SplitPath (path);
168 | if (type === undefined) {
169 | type = s3defaultType;
170 | }
171 | if (acl === undefined) {
172 | acl = s3defaultAcl;
173 | }
174 | var params = {
175 | ACL: acl,
176 | ContentType: type,
177 | Body: data,
178 | Bucket: splitpath.Bucket,
179 | Key: splitpath.Key,
180 | Metadata: metadata
181 | };
182 | s3.putObject (params, function (err, data) {
183 | if (err) {
184 | console.log ("s3NewObject: error == " + err.message);
185 | s3stats.ctWriteErrors++;
186 | if (callback != undefined) {
187 | callback (err, data);
188 | }
189 | }
190 | else {
191 | s3stats.ctWrites++;
192 | s3stats.ctBytesWritten += params.Body.length;
193 | if (callback != undefined) {
194 | callback (err, data);
195 | }
196 | }
197 | });
198 | }
199 | function s3Redirect (path, url) { //1/30/14 by DW -- doesn't appear to work -- don't know why
200 | var splitpath = s3SplitPath (path);
201 | var params = {
202 | WebsiteRedirectLocation: url,
203 | Bucket: splitpath.Bucket,
204 | Key: splitpath.Key,
205 | Body: " "
206 | };
207 | s3.putObject (params, function (err, data) {
208 | if (err != null) {
209 | console.log ("s3Redirect: err.message = " + err.message + ".");
210 | }
211 | else {
212 | console.log ("s3Redirect: path = " + path + ", url = " + url + ", data = ", JSON.stringify (data));
213 | }
214 | });
215 | }
216 | function s3GetObjectMetadata (path, callback) {
217 | var params = s3SplitPath (path);
218 | s3.headObject (params, function (err, data) {
219 | callback (data);
220 | });
221 | }
222 | function s3GetObject (path, callback) {
223 | var params = s3SplitPath (path);
224 | s3.getObject (params, function (err, data) {
225 | if (err) {
226 | s3stats.ctReadErrors++;
227 | }
228 | else {
229 | s3stats.ctReads++;
230 | s3stats.ctBytesRead += data.Body.length;
231 | }
232 | callback (err, data);
233 | });
234 | }
235 | function s3ListObjects (path, callback) {
236 | var splitpath = s3SplitPath (path);
237 | function getNextGroup (marker) {
238 | var params = {Bucket: splitpath.Bucket, Prefix: splitpath.Key};
239 | if (marker != undefined) {
240 | params = {Bucket: splitpath.Bucket, Prefix: splitpath.Key, Marker: marker};
241 | }
242 | s3.listObjects (params, function (err, data) {
243 | if (err) {
244 | console.log ("s3ListObjects: error == " + err.message);
245 | }
246 | else {
247 | var lastobj = data.Contents [data.Contents.length - 1];
248 | for (var i = 0; i < data.Contents.length; i++) {
249 | data.Contents [i].s3path = splitpath.Bucket + "/" + data.Contents [i].Key; //5/22/14 by DW
250 | callback (data.Contents [i]);
251 | }
252 | if (data.IsTruncated) {
253 | getNextGroup (lastobj.Key);
254 | }
255 | else {
256 | var obj = new Object ();
257 | obj.flLastObject = true;
258 | callback (obj);
259 | }
260 | }
261 | });
262 | }
263 | getNextGroup ();
264 | }
265 |
266 |
267 |
268 |
269 |
270 | var taskQ = [];
271 | function qNotEmpty () {
272 | return (taskQ.length > 0);
273 | }
274 | function qSize () {
275 | return (taskQ.length);
276 | }
277 | function qAddTask (taskcode, taskdata) { //add task at end of array
278 | if (taskcode === undefined) {
279 | taskcode = "";
280 | }
281 | if (taskdata === undefined) {
282 | taskdata = {};
283 | }
284 | taskQ [taskQ.length] = {
285 | code: taskcode,
286 | data: taskdata
287 | };
288 | }
289 | function qRunNextTask () { //run the task at the beginning of array
290 | if (qNotEmpty ()) {
291 | var theTask = taskQ [0];
292 | if (theTask.data !== undefined) {
293 | with (theTask.data) {
294 | eval (theTask.code);
295 | }
296 | }
297 | else {
298 | eval (theTask.code);
299 | }
300 | taskQ.splice (0, 1); //remove first item
301 | }
302 | }
303 |
304 |
305 | var riverCache = new Object (), flUseRiverCache = false, flRunningOnServer = true;
306 |
307 | function clearBuildRiverCache () {
308 | riverCache = new Object ();
309 | }
310 | function getCalendarPath (theDay) {
311 | if (theDay == undefined) {
312 | theDay = dayRiverCovers;
313 | }
314 | return (s3CalendarDataFolder + utils.getDatePath (theDay, false) + ".json");
315 | }
316 | function buildOneRiver (listname, flSave, flSkipDuplicateTitles, flAddJsonpWrapper) {
317 | var theRiver = new Object (), starttime = new Date (), ctitems = 0, flEndOfSource = false, titles = new Object (), ctDuplicatesSkipped = 0;
318 | if (flSave == undefined) {
319 | flSave = true;
320 | }
321 | if (flSkipDuplicateTitles == undefined) {
322 | flSkipDuplicateTitles = true;
323 | }
324 | if (flAddJsonpWrapper == undefined) {
325 | flAddJsonpWrapper = true;
326 | }
327 | theRiver.updatedFeeds = new Object ();
328 | theRiver.updatedFeeds.updatedFeed = new Array ();
329 |
330 | function getRiverForDay (d, callback) {
331 | var s3path = getCalendarPath (d);
332 | if (flRunningOnServer) {
333 | stGetObject (s3path, function (error, data) {
334 | if (error) {
335 | callback (undefined);
336 | }
337 | else {
338 | var struct = parseJson (data.Body, s3path);
339 | callback (struct);
340 | }
341 | });
342 | }
343 | else {
344 | var url = "http:/" + s3path;
345 | readHttpFile (url, function (jsontext) {
346 | if (jsontext == undefined) {
347 | callback (undefined);
348 | }
349 | else {
350 | var struct = parseJson (jsontext);
351 | callback (struct);
352 | }
353 | });
354 | }
355 | }
356 | function finishBuild () {
357 | var jsontext;
358 | theRiver.metadata = {
359 | name: listname,
360 | docs: "http://scripting.com/stories/2010/12/06/innovationRiverOfNewsInJso.html",
361 | secs: utils.secondsSince (starttime),
362 | ctDuplicatesSkipped: ctDuplicatesSkipped,
363 | whenGMT: starttime.toUTCString (),
364 | whenLocal: starttime.toLocaleString (),
365 | aggregator: myProductName + " v" + myVersion
366 | };
367 | jsontext = utils.jsonStringify (theRiver, true);
368 | if (flAddJsonpWrapper) {
369 | jsontext = "onGetRiverStream (" + jsontext + ")";
370 | }
371 | if (flSave) {
372 | var fname = utils.stringPopLastField (listname, ".") + ".js";
373 | stNewObject (s3UserRiversPath + fname, jsontext, "application/json", s3defaultAcl, function (error, data) {
374 | console.log ("buildOneRiver: " + s3UserRiversPath + fname + ".");
375 | serverData.stats.ctRiverJsonSaves++;
376 | serverData.stats.whenLastRiverJsonSave = starttime;
377 | });
378 | }
379 | else {
380 | console.log (jsontext);
381 | }
382 | }
383 | function doOneDay (theDay) {
384 | if (flEndOfSource) {
385 | finishBuild ();
386 | }
387 | else {
388 | getRiverForDay (theDay, function (theDaysRiver) {
389 | if (theDaysRiver == undefined) { //error reading the source file
390 | finishBuild ();
391 | }
392 | else {
393 | var lastfeedurl = undefined, theRiverFeed, flThisFeedInList;
394 | for (var i = theDaysRiver.length - 1; i >= 0; i--) {
395 | var story = theDaysRiver [i], flskip = false, reducedtitle;
396 | if (flSkipDuplicateTitles) { //5/29/14 by DW
397 | reducedtitle = utils.trimWhitespace (utils.stringLower (story.title));
398 | if (reducedtitle.length > 0) { //6/6/14 by DW
399 | if (titles [reducedtitle] != undefined) { //duplicate
400 | ctDuplicatesSkipped++;
401 | flskip = true;
402 | }
403 | }
404 | }
405 | if (!flskip) {
406 | if (story.feedUrl != lastfeedurl) {
407 | var feedstats = findInFeedsArray (story.feedUrl);
408 | flThisFeedInList = false;
409 |
410 | if (feedstats !== undefined) { //10/30/15 by DW -- an item appears in a river but we're no longers subscribed to its feed
411 | for (var j = 0; j < feedstats.lists.length; j++) {
412 | if (feedstats.lists [j] == listname) {
413 | flThisFeedInList = true;
414 | break;
415 | }
416 | }
417 | }
418 |
419 | if (flThisFeedInList) {
420 | var ix = theRiver.updatedFeeds.updatedFeed.length;
421 | theRiver.updatedFeeds.updatedFeed [ix] = new Object ();
422 | theRiverFeed = theRiver.updatedFeeds.updatedFeed [ix];
423 |
424 | theRiverFeed.feedTitle = feedstats.title;
425 | theRiverFeed.feedUrl = story.feedUrl;
426 | theRiverFeed.websiteUrl = feedstats.htmlurl;
427 | //description
428 | if (feedstats.description == undefined) {
429 | theRiverFeed.feedDescription = "";
430 | }
431 | else {
432 | theRiverFeed.feedDescription = feedstats.description;
433 | }
434 | //whenLastUpdate -- 6/7/15 by DW
435 | if (story.when !== undefined) {
436 | theRiverFeed.whenLastUpdate = new Date (story.when).toUTCString ();
437 | }
438 | else {
439 | theRiverFeed.whenLastUpdate = new Date (feedstats.whenLastNewItem).toUTCString ();
440 | }
441 | theRiverFeed.item = new Array ();
442 | }
443 |
444 | lastfeedurl = story.feedUrl;
445 | }
446 | if (flThisFeedInList) { //add an item to this set of updates to the feed
447 | var ix = theRiverFeed.item.length, theItem;
448 | theRiverFeed.item [ix] = new Object ();
449 | theItem = theRiverFeed.item [ix];
450 | theItem.title = story.title;
451 | theItem.link = story.link;
452 | theItem.body = story.description;
453 |
454 | if (story.outline != undefined) { //7/16/14 by DW
455 | theItem.outline = story.outline;
456 | }
457 |
458 | theItem.pubDate = new Date (story.pubdate).toUTCString ();
459 | theItem.permaLink = story.permalink;
460 | if (story.comments.length > 0) { //6/7/14 by DW
461 | theItem.comments = story.comments;
462 | }
463 | //enclosure -- 5/30/14 by DW
464 | if (story.enclosure != undefined) {
465 | var flgood = true;
466 |
467 | if ((story.enclosure.type == undefined) || (story.enclosure.length === undefined)) { //both are required
468 | flgood = false; //sorry! :-(
469 | }
470 | else {
471 | if (utils.stringCountFields (story.enclosure.type, "/") < 2) { //something like "image" -- not a valid type
472 | flgood = false; //we read the spec, did you? :-)
473 | }
474 | }
475 |
476 | if (flgood) {
477 | theItem.enclosure = [story.enclosure];
478 | }
479 | }
480 | //id
481 | if (story.id == undefined) {
482 | theItem.id = "";
483 | }
484 | else {
485 | theItem.id = utils.padWithZeros (story.id, 7);
486 | }
487 | if (++ctitems >= serverData.prefs.maxRiverItems) {
488 | flEndOfSource = true;
489 | break;
490 | }
491 | if (flSkipDuplicateTitles) { //5/29/14 by DW -- add the title to the titles object
492 | titles [reducedtitle] = true;
493 | }
494 | }
495 | }
496 | }
497 | doOneDay (utils.dateYesterday (theDay));
498 | }
499 | });
500 | }
501 | }
502 | doOneDay (starttime);
503 | }
504 |
505 | var fsStats = {
506 | ctWrites: 0,
507 | ctBytesWritten: 0,
508 | ctWriteErrors: 0,
509 | ctReads: 0,
510 | ctBytesRead: 0,
511 | ctReadErrors: 0
512 | };
513 |
514 |
515 |
516 | function fsSureFilePath (path, callback) {
517 | var splits = path.split ("/");
518 | path = ""; //1/8/15 by DW
519 | if (splits.length > 0) {
520 | function doLevel (levelnum) {
521 | if (levelnum < (splits.length - 1)) {
522 | path += splits [levelnum] + "/";
523 | fs.exists (path, function (flExists) {
524 | if (flExists) {
525 | doLevel (levelnum + 1);
526 | }
527 | else {
528 | fs.mkdir (path, undefined, function () {
529 | doLevel (levelnum + 1);
530 | });
531 | }
532 | });
533 | }
534 | else {
535 | if (callback != undefined) {
536 | callback ();
537 | }
538 | }
539 | }
540 | doLevel (0);
541 | }
542 | else {
543 | if (callback != undefined) {
544 | callback ();
545 | }
546 | }
547 | }
548 | function fsNewObject (path, data, type, acl, callback, metadata) {
549 | fsSureFilePath (path, function () {
550 | fs.writeFile (path, data, function (err) {
551 | var dataAboutWrite = {
552 | };
553 | if (err) {
554 | console.log ("fsNewObject: error == " + JSON.stringify (err, undefined, 4));
555 | fsStats.ctWriteErrors++;
556 | if (callback != undefined) {
557 | callback (err, dataAboutWrite);
558 | }
559 | }
560 | else {
561 | fsStats.ctWrites++;
562 | fsStats.ctBytesWritten += data.length;
563 | if (callback != undefined) {
564 | callback (err, dataAboutWrite);
565 | }
566 | }
567 | });
568 | });
569 | }
570 | function fsGetObject (path, callback) {
571 | fs.readFile (path, "utf8", function (err, data) {
572 | var dataAboutRead = {
573 | Body: data
574 | };
575 | if (err) {
576 | fsStats.ctReadErrors++;
577 | }
578 | else {
579 | fsStats.ctReads++;
580 | fsStats.ctBytesRead += dataAboutRead.Body.length;
581 | }
582 | callback (err, dataAboutRead);
583 | });
584 | }
585 | function fsListObjects (path, callback) {
586 | function endsWithChar (s, chPossibleEndchar) {
587 | if ((s === undefined) || (s.length == 0)) {
588 | return (false);
589 | }
590 | else {
591 | return (s [s.length - 1] == chPossibleEndchar);
592 | }
593 | }
594 | fs.readdir (path, function (err, list) {
595 | if (!endsWithChar (path, "/")) {
596 | path += "/";
597 | }
598 | if (list !== undefined) { //6/4/15 by DW
599 | for (var i = 0; i < list.length; i++) {
600 | var obj = {
601 | s3path: path + list [i],
602 | path: path + list [i], //11/21/14 by DW
603 | Size: 1
604 | };
605 | callback (obj);
606 | }
607 | }
608 | callback ({flLastObject: true});
609 | });
610 | }
611 |
612 | var localStorage = {
613 | };
614 | var lastLocalStorageJson;
615 |
616 | function loadLocalStorage (callback) {
617 | stGetObject (s3LocalStoragePath, function (error, data) {
618 | if (!error) {
619 | localStorage = parseJson (data.Body, s3LocalStoragePath);
620 | }
621 | if (callback != undefined) {
622 | callback ();
623 | }
624 | });
625 | }
626 | function writeLocalStorageIfChanged () {
627 | var s = utils.jsonStringify (localStorage);
628 | if (s != lastLocalStorageJson) {
629 | lastLocalStorageJson = s;
630 | stNewObject (s3LocalStoragePath, s, "application/json", s3defaultAcl);
631 | }
632 | }
633 |
634 |
635 | function runUserScript (s, dataforscripts, scriptName) {
636 | try {
637 | if (dataforscripts !== undefined) {
638 | with (dataforscripts) {
639 | eval (s);
640 | }
641 | }
642 | else {
643 | eval (s);
644 | }
645 | }
646 | catch (err) {
647 | console.log ("runUserScript: error running \"" + scriptName + "\" == " + err.message);
648 | }
649 | }
650 | function runScriptsInFolder (path, dataforscripts, callback) {
651 | fsSureFilePath (path, function () {
652 | fs.readdir (path, function (err, list) {
653 | for (var i = 0; i < list.length; i++) {
654 | var fname = list [i];
655 | if (utils.endsWith (fname.toLowerCase (), ".js")) {
656 | var f = path + fname;
657 | fs.readFile (f, function (err, data) {
658 | if (err) {
659 | console.log ("runScriptsInFolder: error == " + err.message);
660 | }
661 | else {
662 | runUserScript (data.toString (), dataforscripts, f);
663 | }
664 | });
665 | }
666 | }
667 | if (callback != undefined) {
668 | callback ();
669 | }
670 | });
671 | });
672 | }
673 | function callAddToRiverCallbacks (urlfeed, itemFromParser, itemFromRiver) {
674 | var dataforscripts = {
675 | urlfeed: urlfeed,
676 | itemFromParser: itemFromParser,
677 | itemFromRiver: itemFromRiver
678 | };
679 | runScriptsInFolder (addToRiverCallbacksFolder, dataforscripts, function () {
680 | });
681 | }
682 |
683 |
684 |
685 | //storage routines -- 9/24/14 by DW
686 | function stNewObject (path, data, type, acl, callback, metadata) {
687 | if (fspath != undefined) {
688 | fsNewObject (path, data, type, acl, callback, metadata);
689 | }
690 | else {
691 | s3NewObject (path, data, type, acl, callback, metadata);
692 | }
693 | }
694 | function stGetObject (path, callback) {
695 | if (fspath != undefined) {
696 | fsGetObject (path, callback);
697 | }
698 | else {
699 | s3GetObject (path, callback);
700 | }
701 | }
702 | function stListObjects (path, callback) {
703 | if (fspath != undefined) {
704 | fsSureFilePath (path, function () { //7/19/15 by DW -- create the folder if it doesn't exist
705 | fsListObjects (path, callback);
706 | });
707 | }
708 | else {
709 | s3ListObjects (path, callback);
710 | }
711 | }
712 |
713 | function todaysRiverChanged () { //6/21/15 by DW -- callback scripts, call this to be sure your changes get saved
714 | flRiverDirty = true;
715 | }
716 | function httpReadUrl (url, callback) { //12/1/14 by DW
717 | request (url, function (error, response, body) {
718 | if (!error && (response.statusCode == 200)) {
719 | callback (body)
720 | }
721 | else {
722 | callback (undefined);
723 | }
724 | });
725 | }
726 | function parseJson (jsontext, s3Path) {
727 | var obj;
728 | try {
729 | return (JSON.parse (jsontext));
730 | }
731 | catch (err) {
732 | if (s3Path == undefined) {
733 | console.log ("parseJson, error: " + err.message);
734 | }
735 | else {
736 | console.log ("parseJson, error with S3 file: " + s3Path + ", " + err.message);
737 | }
738 |
739 |
740 | return (new Object ());
741 | }
742 | }
743 | function countHttpSockets () {
744 | var ct = Object.keys (http.globalAgent.requests).length;
745 | if (ct == undefined) {
746 | ct = 0;
747 | }
748 | return (ct);
749 | }
750 | function loadTodaysRiver (callback) {
751 | var s3path = getCalendarPath (dayRiverCovers);
752 | stGetObject (s3path, function (error, data) {
753 | if (!error) {
754 | todaysRiver = parseJson (data.Body, s3path);
755 | }
756 | if (callback != undefined) {
757 | callback ();
758 | }
759 | });
760 | }
761 | function saveTodaysRiver (callback) {
762 | var now = new Date ();
763 | console.log ("saveTodaysRiver: " + getCalendarPath (dayRiverCovers));
764 | stNewObject (getCalendarPath (dayRiverCovers), utils.jsonStringify (todaysRiver, true), "application/json", s3defaultAcl, function (error, data) {
765 | serverData.stats.ctRiverSaves++;
766 | serverData.stats.whenLastRiverSave = now;
767 | if (error) { //4/21/15 by DW -- we were counting errors incorrectly
768 | serverData.stats.ctRiverSaveErrors++;
769 | serverData.stats.whenLastRiverSaveError = now;
770 | }
771 | else {
772 | flRiverDirty = false;
773 | }
774 | if (callback != undefined) {
775 | callback ();
776 | }
777 | });
778 | }
779 | function checkRiverRollover () {
780 | var now = new Date ();
781 | function roll () {
782 | todaysRiver = new Array (); //clear it out
783 | dayRiverCovers = now;
784 | serverData.stats.ctHitsToday = 0;
785 | saveTodaysRiver (); //4/21/15 by DW -- initialize empty river
786 | }
787 | if (utils.secondsSince (serverData.stats.whenLastStoryAdded) >= 60) {
788 | if (!utils.sameDay (now, dayRiverCovers)) { //rollover
789 | if (flRiverDirty) {
790 | saveTodaysRiver (roll);
791 | }
792 | else {
793 | roll ();
794 | }
795 | }
796 | }
797 | }
798 | function addToRiver (urlfeed, itemFromParser, callback) {
799 | var now = new Date (), item = new Object ();
800 | //copy selected elements from the object from feedparser, into the item for the river
801 | function convertOutline (jstruct) { //7/16/14 by DW
802 | var theNewOutline = {}, atts, subs;
803 | if (jstruct ["source:outline"] != undefined) {
804 | if (jstruct ["@"] != undefined) {
805 | atts = jstruct ["@"];
806 | subs = jstruct ["source:outline"];
807 | }
808 | else {
809 | atts = jstruct ["source:outline"] ["@"];
810 | subs = jstruct ["source:outline"] ["source:outline"];
811 | }
812 | }
813 | else {
814 | atts = jstruct ["@"];
815 | subs = undefined;
816 | }
817 | for (var x in atts) {
818 | theNewOutline [x] = atts [x];
819 | }
820 | if (subs != undefined) {
821 | theNewOutline.subs = [];
822 | if (subs instanceof Array) {
823 | for (var i = 0; i < subs.length; i++) {
824 | theNewOutline.subs [i] = convertOutline (subs [i]);
825 | }
826 | }
827 | else {
828 | theNewOutline.subs = [];
829 | theNewOutline.subs [0] = {};
830 | for (var x in subs ["@"]) {
831 | theNewOutline.subs [0] [x] = subs ["@"] [x];
832 | }
833 | }
834 | }
835 | return (theNewOutline);
836 | }
837 | function newConvertOutline (jstruct) { //10/16/14 by DW
838 | var theNewOutline = {};
839 | if (jstruct ["@"] != undefined) {
840 | utils.copyScalars (jstruct ["@"], theNewOutline);
841 | }
842 | if (jstruct ["source:outline"] != undefined) {
843 | if (jstruct ["source:outline"] instanceof Array) {
844 | var theArray = jstruct ["source:outline"];
845 | theNewOutline.subs = [];
846 | for (var i = 0; i < theArray.length; i++) {
847 | theNewOutline.subs [theNewOutline.subs.length] = newConvertOutline (theArray [i]);
848 | }
849 | }
850 | else {
851 | theNewOutline.subs = [
852 | newConvertOutline (jstruct ["source:outline"])
853 | ];
854 | }
855 | }
856 | return (theNewOutline);
857 | }
858 | function getString (s) {
859 | if (s == null) {
860 | s = "";
861 | }
862 | return (utils.stripMarkup (s));
863 | }
864 | function getDate (d) {
865 | if (d == null) {
866 | d = now;
867 | }
868 | return (new Date (d))
869 | }
870 |
871 | item.title = getString (itemFromParser.title);
872 | item.link = getString (itemFromParser.link);
873 | //description
874 | item.description = utils.trimWhitespace (getString (itemFromParser.description));
875 | if (item.description.length > serverData.prefs.maxBodyLength) {
876 | item.description = utils.trimWhitespace (utils.maxStringLength (item.description, serverData.prefs.maxBodyLength));
877 | }
878 | //permalink -- updated 5/30/14 by DW
879 | if (itemFromParser.permalink == undefined) {
880 | item.permalink = "";
881 | }
882 | else {
883 | item.permalink = itemFromParser.permalink;
884 | }
885 |
886 | //enclosure -- 5/30/14 by DW
887 | if (itemFromParser.enclosures != undefined) { //it's an array, we want the first one
888 | item.enclosure = itemFromParser.enclosures [0];
889 | }
890 | //source:outline -- 7/16/14 by DW
891 | if (itemFromParser ["source:outline"] != undefined) { //they're using a cool feature! :-)
892 | item.outline = newConvertOutline (itemFromParser ["source:outline"]);
893 | }
894 | item.pubdate = getDate (itemFromParser.pubDate);
895 | item.comments = getString (itemFromParser.comments);
896 | item.feedUrl = urlfeed;
897 | item.when = now; //6/7/15 by DW
898 | item.aggregator = myProductName + " v" + myVersion;
899 | item.id = serverData.stats.serialnum++; //5/28/14 by DW
900 | todaysRiver [todaysRiver.length] = item;
901 | flRiverDirty = true;
902 | //stats
903 | serverData.stats.ctStoriesAdded++;
904 | serverData.stats.ctStoriesAddedThisRun++;
905 | serverData.stats.whenLastStoryAdded = now;
906 | serverData.stats.lastStoryAdded = item;
907 | //show in console
908 | var consolemsg = itemFromParser.title;
909 | if (consolemsg == null) {
910 | consolemsg = utils.maxStringLength (utils.stripMarkup (itemFromParser.description), 80);
911 | }
912 | console.log ("***addToRiver: " + consolemsg);
913 |
914 | callAddToRiverCallbacks (urlfeed, itemFromParser, todaysRiver [todaysRiver.length - 1]); //6/19/15 by DW
915 | }
916 |
917 | function loadServerData (callback) {
918 | stGetObject (s3PrefsAndStatsPath, function (error, data) {
919 | if (error) {
920 | if (!utils.beginsWith (error.message, "ENOENT")) { //7/19/15 by DW
921 | console.log ("loadServerData: error == " + error.message);
922 | }
923 | }
924 | else {
925 | var oldServerData = parseJson (data.Body, s3PrefsAndStatsPath);
926 | for (var x in oldServerData.prefs) {
927 | serverData.prefs [x] = oldServerData.prefs [x];
928 | }
929 | for (var x in oldServerData.stats) {
930 | serverData.stats [x] = oldServerData.stats [x];
931 | }
932 | serverData.lists = oldServerData.lists;
933 | serverData.flags = oldServerData.flags;
934 | }
935 |
936 | serverData.stats.aggregator = myProductName + " v" + myVersion;
937 | serverData.stats.whenServerStart = new Date ().toLocaleString ();
938 | serverData.stats.ctFeedReadsThisRun = 0;
939 | serverData.stats.ctStoriesAddedThisRun = 0;
940 | serverData.stats.ctHitsThisRun = 0;
941 | serverData.stats.ctServerStarts++;
942 | serverData.stats.ctActiveThreads = 0;
943 |
944 | flHaveServerData = true; //other code can depend on it being intialized
945 |
946 | if (callback != undefined) {
947 | callback ();
948 | }
949 | });
950 | }
951 | function updateStatsBeforeSave () {
952 | var now = new Date ();
953 |
954 | //stats
955 | serverData.stats.ctHoursServerUp = utils.secondsSince (whenServerStart) / 3600;
956 | serverData.stats.secsSinceLastFeedRead = utils.secondsSince (serverData.stats.whenLastFeedRead);
957 | //set whenLastScanBegin and whenLastScanEnd
958 | if (serverData.stats.flScanningNow) {
959 | if (serverData.stats.secsSinceLastFeedRead > 15) {
960 | serverData.stats.ctScans++;
961 | serverData.stats.flScanningNow = false;
962 | serverData.stats.whenLastScanEnd = now;
963 | }
964 | }
965 | else {
966 | if (serverData.stats.secsSinceLastFeedRead < 5) {
967 | if (!serverData.stats.flScanningNow) {
968 | serverData.stats.flScanningNow = true;
969 | serverData.stats.whenLastScanBegin = now;
970 | }
971 | }
972 | }
973 | //s3 stats -- 5/30/14 by DW
974 | serverData.stats.s3stats = s3stats;
975 | //memory stats -- 5/30/14 by DW
976 | serverData.stats.memoryUsage = process.memoryUsage ();
977 | }
978 | function saveServerData () {
979 | updateStatsBeforeSave ();
980 | stNewObject (s3PrefsAndStatsPath, utils.jsonStringify (serverData, true), "application/json", s3defaultAcl);
981 | }
982 |
983 | function addToFeedsInLists (urlfeed) { //5/30/14 by DW
984 | if (feedsInLists [urlfeed] == undefined) {
985 | feedsInLists [urlfeed] = 1;
986 | }
987 | else {
988 | feedsInLists [urlfeed]++;
989 | }
990 | }
991 | function saveFeedsInLists () { //5/30/14 by DW
992 | stNewObject (s3FeedsInListsPath, utils.jsonStringify (feedsInLists, true), "application/json", s3defaultAcl);
993 | }
994 | function atLeastOneSubscriber (urlfeed) {
995 | return (feedsInLists [urlfeed] != undefined);
996 | }
997 |
998 | function initFeedsArrayItem (feedstats) {
999 | if (feedstats.ctReads == undefined) {
1000 | feedstats.ctReads = 0;
1001 | }
1002 | if (feedstats.whenLastRead == undefined) {
1003 | feedstats.whenLastRead = new Date (0);
1004 | }
1005 |
1006 | if (feedstats.ctItems == undefined) {
1007 | feedstats.ctItems = 0;
1008 | }
1009 | if (feedstats.whenLastNewItem == undefined) {
1010 | feedstats.whenLastNewItem = new Date (0);
1011 | }
1012 |
1013 | if (feedstats.ctReadErrors == undefined) {
1014 | feedstats.ctReadErrors = 0;
1015 | }
1016 | if (feedstats.whenLastReadError == undefined) {
1017 | feedstats.whenLastReadError = new Date (0);
1018 | }
1019 | if (feedstats.ctConsecutiveReadErrors == undefined) {
1020 | feedstats.ctConsecutiveReadErrors = 0;
1021 | }
1022 |
1023 | if (feedstats.ctTimesChosen == undefined) {
1024 | feedstats.ctTimesChosen = 0;
1025 | }
1026 | if (feedstats.whenLastChosenToRead == undefined) {
1027 | feedstats.whenLastChosenToRead = new Date (0);
1028 | }
1029 |
1030 | //init cloud stats -- 6/4/15 by DW
1031 | if (feedstats.ctCloudRenew === undefined) {
1032 | feedstats.ctCloudRenew = 0;
1033 | }
1034 | if (feedstats.whenLastCloudRenew === undefined) {
1035 | feedstats.whenLastCloudRenew = new Date (0);
1036 | }
1037 | if (feedstats.ctCloudRenewErrors === undefined) {
1038 | feedstats.ctCloudRenewErrors = 0;
1039 | }
1040 | if (feedstats.ctConsecutiveCloudRenewErrors === undefined) {
1041 | feedstats.ctConsecutiveCloudRenewErrors = 0;
1042 | }
1043 | if (feedstats.whenLastCloudRenewError === undefined) {
1044 | feedstats.whenLastCloudRenewError = new Date (0);
1045 | }
1046 | }
1047 | function addToFeedsArray (urlfeed, obj, listname) {
1048 |
1049 | var lowerfeed = urlfeed.toLowerCase (), flfound = false, ixfeed;
1050 | for (var i = 0; i < feedsArray.length; i++) {
1051 | if (feedsArray [i].url.toLowerCase () == lowerfeed) {
1052 | ixfeed = i;
1053 | flfound = true;
1054 | break;
1055 | }
1056 | }
1057 | if (!flfound) {
1058 | var objnew = new Object ();
1059 | objnew.url = urlfeed;
1060 | objnew.lists = [];
1061 | ixfeed = feedsArray.length;
1062 | feedsArray [ixfeed] = objnew;
1063 | for (var x in obj) { //6/1/14 by DW -- moved into the if, only copy fields if the item is new
1064 | feedsArray [ixfeed] [x] = obj [x];
1065 | }
1066 | }
1067 |
1068 | initFeedsArrayItem (obj);
1069 |
1070 | //add list name to the list of lists this feed belongs to
1071 | var lists = feedsArray [ixfeed].lists, fladd = true;
1072 | for (var i = 0; i < lists.length; i++) {
1073 | if (lists [i] == listname) {
1074 | fladd = false;
1075 | }
1076 | }
1077 | if (fladd) {
1078 | lists [lists.length] = listname;
1079 | }
1080 |
1081 | flFeedsArrayDirty = true;
1082 | }
1083 | function saveFeedsArray () {
1084 | flFeedsArrayDirty = false;
1085 | console.log ("saveFeedsArray: " + s3FeedsArrayPath);
1086 | stNewObject (s3FeedsArrayPath, utils.jsonStringify (feedsArray, true), "application/json", s3defaultAcl);
1087 | }
1088 | function loadFeedsArray (callback) {
1089 | stGetObject (s3FeedsArrayPath, function (error, data) {
1090 | if (!error) {
1091 | feedsArray = parseJson (data.Body, s3FeedsArrayPath);
1092 | for (var i = 0; i < feedsArray.length; i++) {
1093 | initFeedsArrayItem (feedsArray [i]);
1094 | }
1095 | }
1096 | if (callback != undefined) {
1097 | callback ();
1098 | }
1099 | });
1100 | }
1101 | function findInFeedsArray (urlfeed) {
1102 | var lowerfeed = urlfeed.toLowerCase (), flfound = false, ixfeed;
1103 | for (var i = 0; i < feedsArray.length; i++) {
1104 | if (feedsArray [i].url.toLowerCase () == lowerfeed) {
1105 | var feedstats = feedsArray [i];
1106 | initFeedsArrayItem (feedstats);
1107 | return (feedstats);
1108 | }
1109 | }
1110 | return (undefined);
1111 | }
1112 | function findNextFeedToRead () {
1113 | var now = new Date (), whenLeastRecent = now, feedstats = feedsArray [0];
1114 |
1115 | function checkOne (ix) {
1116 | if (atLeastOneSubscriber (feedsArray [ix].url)) {
1117 | var d = feedsArray [ix].whenLastChosenToRead;
1118 | if (d == undefined) { //newly subscribed, it moves to the head of the queue
1119 | d = new Date (0);
1120 | }
1121 | else {
1122 | d = new Date (d);
1123 | }
1124 | if (d < whenLeastRecent) {
1125 | whenLeastRecent = d;
1126 | feedstats = feedsArray [ix];
1127 | }
1128 | }
1129 | }
1130 |
1131 | if (utils.random (0, 1) == 1) {
1132 | for (var i = feedsArray.length - 1; i >= 0; i--) {
1133 | checkOne (i);
1134 | }
1135 | }
1136 | else {
1137 | for (var i = 0; i < feedsArray.length; i++) {
1138 | checkOne (i);
1139 | }
1140 | }
1141 |
1142 | if (feedstats == undefined) {
1143 | return (undefined);
1144 | }
1145 | else {
1146 | if (utils.secondsSince (feedstats.whenLastChosenToRead) < (serverData.prefs.ctMinutesBetwBuilds * 60)) { //not ready to read
1147 | return (undefined);
1148 | }
1149 | else {
1150 | initFeedsArrayItem (feedstats);
1151 | feedstats.ctTimesChosen++;
1152 | feedstats.whenLastChosenToRead = new Date ();
1153 | flFeedsArrayDirty = true;
1154 | return (feedstats);
1155 | }
1156 | }
1157 | }
1158 |
1159 | function getItemGuid (item) {
1160 | function ok (val) {
1161 | if (val != undefined) {
1162 | if (val != "null") {
1163 | return (true);
1164 | }
1165 | }
1166 | return (false);
1167 | }
1168 | if (ok (item.guid)) {
1169 | return (item.guid);
1170 | }
1171 | var guid = "";
1172 | if (ok (item.pubDate)) {
1173 | guid += item.pubDate;
1174 | }
1175 | if (ok (item.link)) {
1176 | guid += item.link;
1177 | }
1178 | if (ok (item.title)) {
1179 | guid += item.title;
1180 | }
1181 | if (guid.length > 0) {
1182 | guid = md5 (guid);
1183 | }
1184 | return (guid);
1185 | }
1186 | function initFeed (urlfeed, callback, flwrite) {
1187 | function cleanFilenameForPlatform (s) { //11/1/14 by DW
1188 | var flprocessed = false;
1189 | if (fspath != undefined) { //we're running on the local file system
1190 | switch (process.platform) { //11/1/14 by DW
1191 | case "win32":
1192 | s = utils.replaceAll (s, "/", "_");
1193 | s = utils.replaceAll (s, "?", "_");
1194 | s = utils.replaceAll (s, ":", "_");
1195 | s = utils.replaceAll (s, "<", "_");
1196 | s = utils.replaceAll (s, ">", "_");
1197 | s = utils.replaceAll (s, "\"", "_");
1198 | s = utils.replaceAll (s, "\\", "_");
1199 | s = utils.replaceAll (s, "|", "_");
1200 | s = utils.replaceAll (s, "*", "_");
1201 | flprocessed = true;
1202 | break;
1203 | }
1204 | }
1205 | if (!flprocessed) {
1206 | s = utils.replaceAll (s, "/", ":");
1207 | }
1208 | return (s);
1209 | }
1210 | function getFolderPath (urlfeed) { //return path to S3 folder for this feed
1211 | var s = urlfeed;
1212 | if (utils.beginsWith (s, "http://")) {
1213 | s = utils.stringDelete (s, 1, 7);
1214 | }
1215 | else {
1216 | if (utils.beginsWith (s, "https://")) {
1217 | s = utils.stringDelete (s, 1, 8);
1218 | }
1219 | }
1220 | s = cleanFilenameForPlatform (s); //11/1/14 by DW
1221 | s = s3FeedsDataFolder + s + "/";
1222 | return (s);
1223 | }
1224 | var folderpath = getFolderPath (urlfeed), infofilepath = folderpath + "feedInfo.json";
1225 | var obj, starttime = new Date ();
1226 | if (flwrite === undefined) {
1227 | flwrite = false;
1228 | }
1229 | stGetObject (infofilepath, function (error, data) {
1230 | if (error) {
1231 | obj = new Object ();
1232 | }
1233 | else {
1234 | obj = parseJson (data.Body, infofilepath);
1235 | }
1236 |
1237 | //prefs
1238 | if (obj.prefs == undefined) {
1239 | obj.prefs = new Object ();
1240 | }
1241 | if (obj.prefs.enabled === undefined) {
1242 | obj.prefs.enabled = true;
1243 | }
1244 | if (obj.prefs.url == undefined) {
1245 | obj.prefs.url = urlfeed;
1246 | }
1247 | if (obj.prefs.ctSecsBetwRenews == undefined) {
1248 | obj.prefs.ctSecsBetwRenews = 24 * 60 * 60; //24 hours
1249 | }
1250 | if (obj.prefs.flNonListSubscribe == undefined) {
1251 | obj.prefs.flNonListSubscribe = false;
1252 | }
1253 | //data
1254 | if (obj.data == undefined) {
1255 | obj.data = new Object ();
1256 | }
1257 | if (obj.data.feedhash == undefined) {
1258 | obj.data.feedhash = "";
1259 | }
1260 | //stats
1261 | if (obj.stats == undefined) {
1262 | obj.stats = new Object ();
1263 | }
1264 | if (obj.stats.s3MyPath == undefined) {
1265 | obj.stats.s3MyPath = infofilepath;
1266 | }
1267 | if (obj.stats.s3FolderPath == undefined) {
1268 | obj.stats.s3FolderPath = folderpath;
1269 | }
1270 | if (obj.stats.ctReads == undefined) {
1271 | obj.stats.ctReads = 0;
1272 | }
1273 | if (obj.stats.ctReadErrors == undefined) {
1274 | obj.stats.ctReadErrors = 0;
1275 | }
1276 | if (obj.stats.ctConsecutiveReadErrors == undefined) {
1277 | obj.stats.ctConsecutiveReadErrors = 0;
1278 | }
1279 | if (obj.stats.whenLastReadError == undefined) {
1280 | obj.stats.whenLastReadError = new Date (0);
1281 | }
1282 | if (obj.stats.lastReadError == undefined) {
1283 | obj.stats.lastReadError = "";
1284 | }
1285 | if (obj.stats.ctItems == undefined) {
1286 | obj.stats.ctItems = 0;
1287 | }
1288 | if (obj.stats.ctEnclosures == undefined) {
1289 | obj.stats.ctEnclosures = 0;
1290 | }
1291 | if (obj.stats.whenLastRead == undefined) {
1292 | obj.stats.whenLastRead = new Date (0);
1293 | }
1294 | if (obj.stats.whenLastNewItem == undefined) {
1295 | obj.stats.whenLastNewItem = new Date (0);
1296 | }
1297 | if (obj.stats.whenSubscribed == undefined) {
1298 | obj.stats.whenSubscribed = new Date ();
1299 | }
1300 | if (obj.stats.ctFeedTextChanges == undefined) {
1301 | obj.stats.ctFeedTextChanges = 0;
1302 | }
1303 | if (obj.stats.ct304s == undefined) {
1304 | obj.stats.ct304s = 0;
1305 | }
1306 | if (obj.stats.mostRecentPubDate == undefined) {
1307 | obj.stats.mostRecentPubDate = new Date (0);
1308 | }
1309 | if (obj.stats.ctItemsTooOld == undefined) {
1310 | obj.stats.ctItemsTooOld = 0;
1311 | }
1312 | if (obj.stats.ctReadsSkipped == undefined) {
1313 | obj.stats.ctReadsSkipped = 0;
1314 | }
1315 | //feedInfo
1316 | if (obj.feedInfo == undefined) {
1317 | obj.feedInfo = new Object ();
1318 | }
1319 | if (obj.feedInfo.title == undefined) {
1320 | obj.feedInfo.title = "";
1321 | }
1322 | if (obj.feedInfo.link == undefined) {
1323 | obj.feedInfo.link = "";
1324 | }
1325 | if (obj.feedInfo.description == undefined) {
1326 | obj.feedInfo.description = "";
1327 | }
1328 | //misc
1329 | if (obj.history == undefined) {
1330 | obj.history = new Array ();
1331 | }
1332 | if (obj.lists == undefined) {
1333 | obj.lists = new Array ();
1334 | }
1335 | if (obj.calendar == undefined) {
1336 | obj.calendar = new Object ();
1337 | }
1338 |
1339 | obj.stats.secsLastInit = secsLastInit; //debugging
1340 |
1341 | if (callback != undefined) {
1342 | callback (obj);
1343 | }
1344 |
1345 | if (flwrite) {
1346 | stNewObject (infofilepath, utils.jsonStringify (obj, true), "application/json", s3defaultAcl, function (error, data) {
1347 | secsLastInit = utils.secondsSince (starttime);
1348 | });
1349 | }
1350 | else {
1351 | secsLastInit = utils.secondsSince (starttime);
1352 | }
1353 | });
1354 | }
1355 | function saveFeed (feed, callback) {
1356 | stNewObject (feed.stats.s3MyPath, utils.jsonStringify (feed, true), "application/json", s3defaultAcl, function (error, data) {
1357 | if (callback !== undefined) { //6/5/15 by DW
1358 | callback ();
1359 | }
1360 | });
1361 | }
1362 | function readFeed (urlfeed, callback) {
1363 | var starttime = new Date ();
1364 | var itemsInFeed = new Object (); //6/3/15 by DW
1365 | initFeed (urlfeed, function (feed) {
1366 | if (feed.prefs.enabled) {
1367 | var ctitemsthisfeed = 0, flfirstread = feed.stats.ctReads == 0, feedstats;
1368 | feedstats = findInFeedsArray (urlfeed); //the in-memory feed stats, stuff the scanner uses to figure out which feed to read next
1369 | //stats
1370 | serverData.stats.ctFeedReads++;
1371 | serverData.stats.ctFeedReadsLastHour++;
1372 | serverData.stats.ctFeedReadsThisRun++;
1373 | serverData.stats.lastFeedRead = urlfeed;
1374 | serverData.stats.whenLastFeedRead = starttime;
1375 |
1376 | feed.stats.ctReads++;
1377 | feed.stats.whenLastRead = starttime;
1378 |
1379 | feedstats.ctReads++;
1380 | feedstats.whenLastRead = starttime;
1381 |
1382 | console.log ("readFeed: " + urlfeed);
1383 |
1384 | flFeedsArrayDirty = true;
1385 | serverData.stats.ctActiveThreads++;
1386 | if (utils.beginsWith (urlfeed, "feed://")) { //8/13/15 by DW
1387 | urlfeed = "http://" + utils.stringDelete (urlfeed, 1, 7);
1388 | }
1389 | var req = request (urlfeed);
1390 | var feedparser = new FeedParser ();
1391 | req.on ("response", function (res) {
1392 | var stream = this;
1393 | serverData.stats.ctActiveThreads--;
1394 | if (res.statusCode == 200) {
1395 | stream.pipe (feedparser);
1396 | }
1397 | });
1398 | req.on ("error", function (res) {
1399 | feed.stats.ctReadErrors++;
1400 | feed.stats.ctConsecutiveReadErrors++;
1401 | feed.stats.whenLastReadError = starttime;
1402 |
1403 | feedstats.ctReadErrors++;
1404 | feedstats.ctConsecutiveReadErrors++;
1405 | feedstats.whenLastReadError = starttime;
1406 |
1407 | serverData.stats.ctActiveThreads--;
1408 | });
1409 | feedparser.on ("readable", function () {
1410 | var item = this.read (), flnew;
1411 | if (new Date (item.pubDate) > new Date (feed.stats.mostRecentPubDate)) {
1412 | feed.stats.mostRecentPubDate = item.pubDate;
1413 | feedstats.mostRecentPubDate = item.pubDate;
1414 | }
1415 |
1416 | //set flnew -- do the history thing
1417 | var theGuid = getItemGuid (item);
1418 | itemsInFeed [theGuid] = true; //6/3/15 by DW
1419 | flnew = true;
1420 | for (var i = 0; i < feed.history.length; i++) {
1421 | if (feed.history [i].guid == theGuid) { //we've already seen it
1422 | flnew = false;
1423 | break;
1424 | }
1425 | }
1426 | if (flnew) { //add to the history array
1427 | var obj = new Object (), flAddToRiver = true;
1428 | obj.title = item.title; //helps with debugging
1429 | obj.guid = theGuid;
1430 | obj.when = starttime;
1431 | feed.history [feed.history.length] = obj;
1432 |
1433 | //stats
1434 | feed.stats.ctItems++;
1435 | feed.stats.whenLastNewItem = starttime;
1436 |
1437 | feedstats.ctItems++;
1438 | feedstats.whenLastNewItem = starttime;
1439 |
1440 |
1441 | //copy feed info from item into the feed record -- 6/1/14 by DW
1442 | feed.feedInfo.title = item.meta.title;
1443 | feed.feedInfo.link = item.meta.link;
1444 | feed.feedInfo.description = item.meta.description;
1445 | //copy cloud info, if present -- 6/3/15 by DW
1446 | if (item.meta.cloud !== undefined) {
1447 | if (item.meta.cloud.domain !== undefined) {
1448 | feed.feedInfo.cloud = {
1449 | domain: item.meta.cloud.domain,
1450 | port: item.meta.cloud.port,
1451 | path: item.meta.cloud.path,
1452 | port: item.meta.cloud.port,
1453 | registerProcedure: item.meta.cloud.registerprocedure,
1454 | protocol: item.meta.cloud.protocol
1455 | };
1456 | feedstats.cloud = {
1457 | domain: item.meta.cloud.domain,
1458 | port: item.meta.cloud.port,
1459 | path: item.meta.cloud.path,
1460 | port: item.meta.cloud.port,
1461 | registerProcedure: item.meta.cloud.registerprocedure,
1462 | protocol: item.meta.cloud.protocol,
1463 | };
1464 | }
1465 | }
1466 | //copy feeds info from item into feeds in-memory array element -- 6/1/14 by DW
1467 | feedstats.title = item.meta.title;
1468 | feedstats.text = item.meta.title;
1469 | feedstats.htmlurl = item.meta.link;
1470 | feedstats.description = item.meta.description;
1471 | flFeedsArrayDirty = true;
1472 |
1473 | //exclude items that newly appear in feed but have a too-old pubdate
1474 | if ((item.pubDate != null) && (new Date (item.pubDate) < utils.dateYesterday (feed.stats.mostRecentPubDate)) && (!flfirstread)) {
1475 | flAddToRiver = false;
1476 | feed.stats.ctItemsTooOld++;
1477 | feed.stats.whenLastTooOldItem = starttime;
1478 | }
1479 | if ((flAddToRiver) && (!flfirstread)) {
1480 | addToRiver (urlfeed, item);
1481 | }
1482 | }
1483 |
1484 | if (serverData.prefs.flWriteItemsToFiles) { //debugging
1485 | var path = feed.stats.s3FolderPath + "items/" + utils.padWithZeros (ctitemsthisfeed++, 3) + ".json";
1486 | stNewObject (path, utils.jsonStringify (item, true), "application/json", s3defaultAcl);
1487 | }
1488 | });
1489 | feedparser.on ("end", function () {
1490 | //delete items in the history array that are no longer in the feed -- 6/3/15 by DW
1491 | var ctHistoryItemsDeleted = 0;
1492 | for (var i = feed.history.length - 1; i >= 0; i--) { //6/3/15 by DW
1493 | if (itemsInFeed [feed.history [i].guid] === undefined) { //it's no longer in the feed
1494 | feed.history.splice (i, 1);
1495 | ctHistoryItemsDeleted++;
1496 | }
1497 | }
1498 | if (ctHistoryItemsDeleted > 0) {
1499 | console.log ("readFeed: ctHistoryItemsDeleted == " + ctHistoryItemsDeleted);
1500 | }
1501 |
1502 | feed.stats.ctSecsLastRead = utils.secondsSince (starttime);
1503 | saveFeed (feed, function () {
1504 | if (callback !== undefined) { //6/5/15 by DW
1505 | callback ();
1506 | }
1507 | });
1508 | });
1509 | feedparser.on ("error", function () {
1510 | feed.stats.ctReadErrors++;
1511 | feed.stats.ctConsecutiveReadErrors++;
1512 | feed.stats.whenLastReadError = starttime;
1513 | });
1514 | }
1515 | });
1516 | }
1517 |
1518 | function readIncludedList (listname, urloutline) { //6/17/14 by DW
1519 | var req = request (urloutline);
1520 | var opmlparser = new OpmlParser ();
1521 |
1522 | console.log ("readIncludedList: listname == " + listname + ", urloutline == " + urloutline);
1523 |
1524 | req.on ("response", function (res) {
1525 | var stream = this;
1526 | if (res.statusCode == 200) {
1527 | stream.pipe (opmlparser);
1528 | }
1529 | });
1530 | req.on ("error", function (res) {
1531 | });
1532 | opmlparser.on ("error", function (error) {
1533 | console.log ("readIncludedList: opml parser error == " + error.message);
1534 | });
1535 | opmlparser.on ("readable", function () {
1536 | var outline;
1537 | while (outline = this.read ()) {
1538 | var type = outline ["#type"];
1539 | if (type == "feed") {
1540 | if ((outline.xmlurl != undefined) && (outline.xmlurl.length > 0)) { //6/9/14 by DW
1541 | addToFeedsArray (outline.xmlurl, outline, listname);
1542 | addToFeedsInLists (outline.xmlurl); //5/30/14 by DW
1543 | }
1544 | }
1545 | }
1546 | });
1547 | opmlparser.on ("end", function () {
1548 | });
1549 | }
1550 | function readOneList (listname, filepath) {
1551 | console.log ("readOneList: listname == " + listname + ", filepath == " + filepath);
1552 | var opmlparser = new OpmlParser ();
1553 | opmlparser.on ("error", function (error) {
1554 | console.log ("scanner: opml parser error == " + error.message);
1555 | });
1556 | opmlparser.once ("readable", function () {
1557 | });
1558 | opmlparser.on ("readable", function () {
1559 | var outline;
1560 | while (outline = this.read ()) {
1561 | var type = outline ["#type"];
1562 |
1563 | if (type == "feed") {
1564 | if ((outline.xmlurl != undefined) && (outline.xmlurl.length > 0)) { //6/9/14 by DW
1565 | addToFeedsArray (outline.xmlurl, outline, listname);
1566 | addToFeedsInLists (outline.xmlurl); //5/30/14 by DW
1567 | }
1568 | }
1569 | else { //6/17/14 by DW
1570 | if (outline.type != undefined) {
1571 | if (outline.type == "include") {
1572 | qAddTask ("readIncludedList (\"" + listname + "\", \"" + outline.url + "\")");
1573 | }
1574 | }
1575 | }
1576 | }
1577 | });
1578 | opmlparser.on ("end", function () {
1579 | });
1580 | stGetObject (filepath, function (error, data) {
1581 | if (error) {
1582 | console.log ("readOneList: error == " + error.message);
1583 | }
1584 | else {
1585 | opmlparser.end (data.Body.toString ());
1586 | }
1587 | });
1588 | }
1589 | function initList (name, callback) {
1590 | var foldername = name, infofilepath;
1591 | if (utils.endsWith (foldername, ".opml")) {
1592 | foldername = utils.stringDelete (foldername, foldername.length - 4, 5);
1593 | }
1594 | infofilepath = s3ListsDataFolder + foldername + "/listInfo.json";
1595 | stGetObject (infofilepath, function (error, data) {
1596 | if (error) {
1597 | obj = new Object ();
1598 | }
1599 | else {
1600 | obj = parseJson (data.Body, infofilepath);
1601 | }
1602 |
1603 | //prefs
1604 | if (obj.prefs == undefined) {
1605 | obj.prefs = new Object ();
1606 | }
1607 | if (obj.prefs.enabled == undefined) {
1608 | obj.prefs.enabled = true;
1609 | }
1610 | //stats
1611 | if (obj.stats == undefined) {
1612 | obj.stats = new Object ();
1613 | }
1614 | if (obj.stats.ctReads == undefined) {
1615 | obj.stats.ctReads = 0;
1616 | }
1617 | if (obj.stats.whenLastRead == undefined) {
1618 | obj.stats.whenLastRead = new Date (0);
1619 | }
1620 | if (obj.stats.whenSubscribed == undefined) {
1621 | obj.stats.whenSubscribed = new Date ();
1622 | }
1623 | if (obj.stats.ctBlockedItems == undefined) {
1624 | obj.stats.ctBlockedItems = 0;
1625 | }
1626 | //listInfo
1627 | if (obj.listInfo == undefined) {
1628 | obj.listInfo = new Object ();
1629 | }
1630 | if (obj.listInfo.title == undefined) {
1631 | obj.listInfo.title = "";
1632 | }
1633 | //misc
1634 | if (obj.feeds == undefined) {
1635 | obj.feeds = new Array ();
1636 | }
1637 | if (obj.feedsBlocked == undefined) {
1638 | obj.feedsBlocked = new Array ();
1639 | }
1640 | if (obj.calendar == undefined) {
1641 | obj.calendar = new Object ();
1642 | }
1643 | if (obj.river == undefined) {
1644 | obj.river = new Object ();
1645 | }
1646 |
1647 | if (callback != undefined) {
1648 | callback (obj);
1649 | }
1650 |
1651 | stNewObject (infofilepath, utils.jsonStringify (obj, true), "application/json", s3defaultAcl, function (error, data) {
1652 | });
1653 | });
1654 | }
1655 | function loadListsFromFolder () {
1656 | var now = new Date ();
1657 | for (var i = 0; i < feedsArray.length; i++) { //6/7/14 by DW
1658 | feedsArray [i].lists = [];
1659 | }
1660 | serverData.stats.ctListFolderReads++;
1661 | serverData.stats.whenLastListFolderRead = now;
1662 | serverData.stats.listNames = new Array ();
1663 | feedsInLists = new Object ();
1664 | stListObjects (s3UserListsPath, function (obj) { //read user's list files
1665 | if (obj.flLastObject != undefined) {
1666 | }
1667 | else {
1668 | if (obj.Size > 0) { //it's a file
1669 | var filepath = obj.s3path;
1670 | var listname = utils.stringNthField (filepath, "/", utils.stringCountFields (filepath, "/")); //something like myList.opml
1671 | if (utils.endsWith (listname, ".opml")) { //11/1/14 by DW
1672 | serverData.stats.listNames [serverData.stats.listNames.length] = listname; //5/28/14 by DW
1673 | initList (listname, function () {
1674 | qAddTask ("readOneList (\"" + listname + "\", \"" + filepath + "\")");
1675 | });
1676 | }
1677 | }
1678 | }
1679 | });
1680 | }
1681 |
1682 | function getAllLists (callback) {
1683 | var theLists = new Array ();
1684 | function getOneFile (ix) {
1685 | if (ix >= serverData.stats.listNames.length) {
1686 | callback (theLists);
1687 | }
1688 | else {
1689 | var fname = serverData.stats.listNames [ix], f = s3UserListsPath + fname;
1690 | stGetObject (f, function (error, data) {
1691 | if (error) {
1692 | console.log ("getAllLists: error reading list " + fname + " error == " + error.message);
1693 | }
1694 | else {
1695 | theLists [theLists.length] = {
1696 | listname: fname,
1697 | opmltext: data.Body.toString ()
1698 | };
1699 | }
1700 | getOneFile (ix + 1);
1701 | });
1702 | }
1703 | }
1704 | getOneFile (0);
1705 | }
1706 | function getOneFeed (urlfeed, callback) { //11/26/14 by DW
1707 | initFeed (urlfeed, function (feed) {
1708 | callback (feed);
1709 | });
1710 | }
1711 | function getOneRiver (fname, callback) { //11/28/14 by DW
1712 | var name = utils.stringPopLastField (fname, "."); //get rid of .opml extension if present
1713 | var path = s3UserRiversPath + name + ".js";
1714 | stGetObject (path, function (error, data) {
1715 | var s;
1716 | if (error) {
1717 | s = "";
1718 | console.log ("getOneRiver: error == " + utils.jsonStringify (error));
1719 | }
1720 | else {
1721 | s = data.Body.toString ();
1722 | }
1723 | if (callback != undefined) {
1724 | callback (s);
1725 | }
1726 | });
1727 | }
1728 | function getFeedMetadata (url, callback) { //12/1/14 by DW
1729 | var req = request (url), feedparser = new FeedParser ();
1730 | req.on ("response", function (res) {
1731 | var stream = this;
1732 | if (res.statusCode == 200) {
1733 | stream.pipe (feedparser);
1734 | }
1735 | else {
1736 | callback (undefined);
1737 | }
1738 | });
1739 | req.on ("error", function (res) {
1740 | callback (undefined);
1741 | });
1742 | feedparser.on ("readable", function () {
1743 | var item = this.read ();
1744 | callback (item.meta);
1745 | });
1746 | feedparser.on ("end", function () {
1747 | callback (undefined);
1748 | });
1749 | feedparser.on ("error", function () {
1750 | callback (undefined);
1751 | });
1752 | }
1753 | function saveSubscriptionList (listname, xmltext) { //12/1/14 by DW
1754 | var path = s3UserListsPath + listname, now = new Date ();
1755 | stNewObject (path, xmltext, "text/xml", s3defaultAcl, function (error, data) {
1756 | var serialnum = utils.padWithZeros (++serverData.stats.backupSerialnum, 3);
1757 | var fname = utils.stringPopLastField (listname, ".") + serialnum + ".opml"; //something like movies024.opml
1758 | var backuppath = s3BackupsFolder + utils.getDatePath (undefined, true) + fname;
1759 | stNewObject (backuppath, xmltext, "text/xml", s3defaultAcl, function (error, data) {
1760 | serverData.stats.ctListSaves++;
1761 | serverData.stats.whenLastListSave = now;
1762 | readOneList (listname, path);
1763 | });
1764 | });
1765 | }
1766 |
1767 | function pleaseNotify (urlServer, domain, port, path, urlFeed, feedstats, callback) { //6/4/15 by DW
1768 | var now = new Date ();
1769 | var theRequest = {
1770 | url: urlServer,
1771 | followRedirect: true,
1772 | headers: {Accept: "application/json"},
1773 | method: "POST",
1774 | form: {
1775 | port: port,
1776 | path: path,
1777 | url1: urlFeed,
1778 | protocol: "http-post"
1779 | }
1780 | };
1781 | request (theRequest, function (error, response, body) {
1782 | try {
1783 | if (!error && (response.statusCode == 200)) {
1784 | feedstats.ctConsecutiveCloudRenewErrors = 0;
1785 | if (callback) {
1786 | callback ();
1787 | }
1788 | }
1789 | else {
1790 | console.log ("pleaseNotify: urlServer == " + urlServer + ", error, code == " + response.statusCode + ".\n");
1791 | feedstats.ctCloudRenewErrors++; //counts the number of communication errors
1792 | feedstats.ctConsecutiveCloudRenewErrors++;
1793 | feedstats.whenLastCloudRenewError = now;
1794 | }
1795 | }
1796 | catch (err) {
1797 | console.log ("pleaseNotify: urlServer == " + urlServer + ", err.message == " + err.message);
1798 | feedstats.ctCloudRenewErrors++; //counts the number of communication errors
1799 | feedstats.ctConsecutiveCloudRenewErrors++;
1800 | feedstats.whenLastCloudRenewError = now;
1801 | }
1802 | feedstats.ctCloudRenew++;
1803 | feedstats.whenLastCloudRenew = now;
1804 | flFeedsArrayDirty = true; //because we modified feedstats
1805 | });
1806 | }
1807 | function renewNextSubscription () { //6/4/15 by DW
1808 | if (serverData.prefs.flRequestCloudNotify) {
1809 | var theFeed;
1810 | for (var i = 0; i < feedsArray.length; i++) {
1811 | theFeed = feedsArray [i];
1812 | if (theFeed.cloud !== undefined) {
1813 | if (utils.secondsSince (theFeed.whenLastCloudRenew) > (23 * 60 * 60)) { //ready to be renewed
1814 | var urlCloudServer = "http://" + theFeed.cloud.domain + ":" + theFeed.cloud.port + theFeed.cloud.path;
1815 | pleaseNotify (urlCloudServer, undefined, myPort, "/feedupdated", theFeed.url, theFeed, function () {
1816 | console.log ("renewNextSubscription: urlCloudServer == " + urlCloudServer);
1817 | });
1818 | return; //we renew at most one each time we're called
1819 | }
1820 | }
1821 | }
1822 | }
1823 | }
1824 | function rssCloudFeedUpdated (urlFeed) { //6/4/15 by DW
1825 | var feedstats = findInFeedsArray (urlFeed);
1826 | if (feedstats === undefined) {
1827 | console.log ("\nrssCloudFeedUpdated: url == " + urlFeed + ", but we're not subscribed to this feed, so it wasn't read.\n");
1828 | }
1829 | else {
1830 | var now = new Date ();
1831 | serverData.stats.whenLastRssCloudUpdate = now;
1832 | serverData.stats.ctRssCloudUpdates++;
1833 | console.log ("\nrssCloudFeedUpdated: url == " + urlFeed + ", now == " + now.toLocaleString ());
1834 | readFeed (urlFeed, function () {
1835 | for (var i = 0; i < feedstats.lists.length; i++) {
1836 | var listname = "\"" + feedstats.lists [i] + "\"";
1837 | var flskip = serverData.prefs.flSkipDuplicateTitles;
1838 | var s = "buildOneRiver (" + listname + ", true, " + flskip + ", true);";
1839 | console.log ("rssCloudFeedUpdated: " + s);
1840 | qAddTask (s);
1841 | }
1842 | });
1843 | }
1844 | }
1845 |
1846 | function applyPrefs () {
1847 | http.globalAgent.maxSockets = serverData.prefs.maxThreads * 5;
1848 | https.globalAgent.maxSockets = serverData.prefs.maxThreads * 5;
1849 | }
1850 | function copyIndexFile () { //6/1/14 by DW
1851 | if (serverData.prefs.enabled) {
1852 | stGetObject (s3IndexFile, function (error, data) {
1853 | if (error) {
1854 | request (urlIndexSource, function (error, response, htmltext) {
1855 | if (!error && response.statusCode == 200) {
1856 | stNewObject (s3IndexFile, htmltext, "text/html", s3defaultAcl, function (error, data) {
1857 | });
1858 | }
1859 | });
1860 | }
1861 | });
1862 | }
1863 | }
1864 | function buildRiversArray () { //6/1/14 by DW -- build a data structure used by the river browser
1865 | var riversArray = new Array ();
1866 | for (var i = 0; i < serverData.stats.listNames.length; i++) {
1867 | var obj = new Object (), rivername = utils.stringPopLastField (serverData.stats.listNames [i], ".");
1868 | obj.url = "rivers/" + rivername + ".js"; //designed for an app running at the top level of the bucket
1869 | obj.title = rivername;
1870 | obj.longTitle = rivername;
1871 | obj.description = "";
1872 | riversArray [i] = obj;
1873 | }
1874 | stNewObject (s3RiversArrayPath, utils.jsonStringify (riversArray, true), "application/json", s3defaultAcl, function (error, data) {
1875 | console.log ("buildRiversArray: " + s3RiversArrayPath);
1876 | });
1877 | }
1878 | function buildAllRivers () { //queue up tasks to build each of the river.js files
1879 | for (var i = 0; i < serverData.stats.listNames.length; i++) {
1880 | var listname = "\"" + serverData.stats.listNames [i] + "\"";
1881 | var flskip = serverData.prefs.flSkipDuplicateTitles;
1882 | var s = "buildOneRiver (" + listname + ", true, " + flskip + ", true);";
1883 | qAddTask (s);
1884 | }
1885 | whenLastRiversBuild = new Date (); //8/6/14 by DW
1886 | }
1887 | function getAppModDate (callback) { //8/21/15 by DW
1888 | fs.exists (fnameApp, function (flExists) {
1889 | if (flExists) {
1890 | fs.stat (fnameApp, function (err, stats) {
1891 | if (err) {
1892 | callback (undefined);
1893 | }
1894 | else {
1895 | callback (new Date (stats.mtime).toString ());
1896 | }
1897 | });
1898 | }
1899 | else {
1900 | callback (undefined);
1901 | }
1902 | });
1903 | }
1904 | function everyQuarterSecond () {
1905 | if (serverData.prefs.enabled) {
1906 | if (countHttpSockets () < serverData.prefs.maxThreads) {
1907 | qRunNextTask ();
1908 | }
1909 | }
1910 | }
1911 | function everyFiveMinutes () {
1912 | if (serverData.prefs.enabled) {
1913 | buildAllRivers ();
1914 | buildRiversArray ();
1915 | }
1916 | }
1917 | function everyMinute () {
1918 | try {
1919 | var now = new Date (), enabledMessage = "";
1920 | serverData.stats.ctHttpSockets = countHttpSockets ();
1921 | serverData.stats.ctMinutes++;
1922 |
1923 | renewNextSubscription (); //6/4/15 by DW
1924 | writeLocalStorageIfChanged (); //6/20/15 by DW
1925 |
1926 | if (!serverData.prefs.enabled) { //12/4/14 by DW
1927 | enabledMessage = " server is not enabled.";
1928 | }
1929 |
1930 | console.log ("\neveryMinute: " + now.toLocaleTimeString () + ", " + qSize () + " items on the task queue, " + serverData.stats.ctHttpSockets + " sockets open, " + feedsArray.length + " feeds." + enabledMessage + " v" + myVersion);
1931 |
1932 | clearBuildRiverCache ();
1933 |
1934 | if (serverData.prefs.enabled) {
1935 | if (flHaveServerData) {
1936 | //check for hour rollover
1937 | if (now.getHours () != whenLastEveryMinute.getHours ()) {
1938 | serverData.stats.ctFeedReadsLastHour = 0;
1939 | }
1940 | whenLastEveryMinute = now;
1941 | saveServerData ();
1942 |
1943 | if (flRiverDirty) {
1944 | saveTodaysRiver ();
1945 | }
1946 | checkRiverRollover ();
1947 |
1948 | if (flFeedsArrayDirty) {
1949 | saveFeedsArray ();
1950 | }
1951 | if (flFeedsInListsDirty) {
1952 | saveFeedsInLists ();
1953 | flFeedsInListsDirty = false;
1954 | }
1955 |
1956 | if (utils.secondsSince (whenLastRiversBuild) >= 59) { //8/6/14 by DW
1957 | loadListsFromFolder ();
1958 | flFeedsInListsDirty = true;
1959 | }
1960 | }
1961 | }
1962 | }
1963 | catch (err) {
1964 | console.log ("everyMinute, error == " + err.message);
1965 | }
1966 | }
1967 | function everySecond () {
1968 | if (!flScheduledEveryMinute) { //8/22/15 by DW
1969 | if (new Date ().getSeconds () == 0) {
1970 | setInterval (everyMinute, 60000);
1971 | setInterval (everyFiveMinutes, 300000);
1972 | flScheduledEveryMinute = true;
1973 | everyMinute (); //it's the top of the minute, we have to do one now
1974 | }
1975 | }
1976 | if (flWatchAppDateChange) { //8/21/15 by DW
1977 | getAppModDate (function (theModDate) {
1978 | if (theModDate != origAppModDate) {
1979 | console.log ("everySecond: " + fnameApp + " has been updated. " + myProductName + " is quitting now.");
1980 | process.exit (0);
1981 | }
1982 | });
1983 | }
1984 | if (serverData.prefs.enabled) {
1985 | var ct = serverData.prefs.ctReadsPerSecond;
1986 | for (var i = 0; i < ct; i++) {
1987 | if (countHttpSockets () <= serverData.prefs.maxThreads) {
1988 | var feedstats = findNextFeedToRead ();
1989 | if (feedstats !== undefined) { //a feed is ready to read
1990 | readFeed (feedstats.url);
1991 | }
1992 | }
1993 | }
1994 | }
1995 | }
1996 |
1997 | function handleRequest (httpRequest, httpResponse) {
1998 | function writeHead (type) {
1999 | if (type == undefined) {
2000 | type = "text/plain";
2001 | }
2002 | httpResponse.writeHead (200, {"Content-Type": type, "Access-Control-Allow-Origin": "*"});
2003 | }
2004 | function respondWithObject (obj) {
2005 | writeHead ("application/json");
2006 | httpResponse.end (utils.jsonStringify (obj));
2007 | }
2008 | try {
2009 | var parsedUrl = urlpack.parse (httpRequest.url, true), now = new Date (), startTime = now;
2010 | var lowerpath = parsedUrl.pathname.toLowerCase (), host, port = 80, flLocalRequest = false;
2011 |
2012 | //set host, port, flLocalRequest
2013 | host = httpRequest.headers.host;
2014 | if (utils.stringContains (host, ":")) {
2015 | port = utils.stringNthField (host, ":", 2);
2016 | host = utils.stringNthField (host, ":", 1);
2017 | }
2018 | flLocalRequest = utils.beginsWith (host, "localhost");
2019 | //show the request on the console
2020 | var localstring = "";
2021 | if (flLocalRequest) {
2022 | localstring = "* ";
2023 | }
2024 | console.log (localstring + httpRequest.method + " " + host + ":" + port + " " + lowerpath);
2025 |
2026 | //stats
2027 | serverData.stats.ctHits++;
2028 | serverData.stats.ctHitsToday++;
2029 | serverData.stats.ctHitsThisRun++;
2030 | switch (httpRequest.method) {
2031 | case "GET":
2032 | switch (lowerpath) {
2033 | case "/": //7/4/15 by DW
2034 | httpResponse.writeHead (200, {"Content-Type": "text/html"});
2035 | request (urlServerHomePageSource, function (error, response, htmltext) {
2036 | if (!error && response.statusCode == 200) {
2037 | httpResponse.end (htmltext);
2038 | }
2039 | });
2040 | break;
2041 | case "/version":
2042 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2043 | httpResponse.end (myVersion);
2044 | break;
2045 | case "/now":
2046 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2047 | httpResponse.end (now.toString ());
2048 | break;
2049 | case "/status":
2050 | var myStatus = {
2051 | version: myVersion,
2052 | now: now.toUTCString (),
2053 | whenServerStart: whenServerStart.toUTCString (),
2054 | s3Path: s3path, //7/31/14 by DW
2055 | port: myPort, //7/31/14 by DW
2056 | defaultAcl: s3defaultAcl, //7/31/14 by DW
2057 | hits: serverData.stats.ctHits,
2058 | hitsToday: serverData.stats.ctHitsToday,
2059 | hitsThisRun: serverData.stats.ctHitsThisRun
2060 | };
2061 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2062 | httpResponse.end (utils.jsonStringify (myStatus, true));
2063 | break;
2064 | case "/serverdata":
2065 | updateStatsBeforeSave ();
2066 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2067 | httpResponse.end (utils.jsonStringify (serverData.stats, true));
2068 | break;
2069 | case "/feedstats":
2070 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2071 | httpResponse.end (utils.jsonStringify (feedsArray, true));
2072 | break;
2073 | case "/buildallrivers":
2074 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2075 | if (serverData.prefs.enabled) {
2076 | buildAllRivers ();
2077 | httpResponse.end ("Your rivers are building sir or madam.");
2078 | }
2079 | else {
2080 | httpResponse.end ("Can't build the rivers because serverData.prefs.enabled is false.");
2081 | }
2082 | break;
2083 | case "/loadlists":
2084 | loadListsFromFolder ();
2085 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2086 | httpResponse.end ("We're reading the lists, right now, as we speak.");
2087 | case "/dashboard": //6/2/14 by DW
2088 | httpResponse.writeHead (200, {"Content-Type": "text/html"});
2089 | request (urlDashboardSource, function (error, response, htmltext) {
2090 | if (!error && response.statusCode == 200) {
2091 | httpResponse.end (htmltext);
2092 | }
2093 | });
2094 | break;
2095 | case "/ping": //9/11/14 by DW
2096 | var url = parsedUrl.query.url;
2097 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2098 | if (findInFeedsArray (url) == undefined) {
2099 | httpResponse.end ("Ping received, but we're not following this feed. Sorry.");
2100 | }
2101 | else {
2102 | httpResponse.end ("Ping received, will read asap.");
2103 | readFeed (url);
2104 | }
2105 | break;
2106 | case "/getlistnames": //11/11/14 by DW
2107 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2108 | httpResponse.end (utils.jsonStringify (serverData.stats.listNames));
2109 | break;
2110 | case "/getalllists": //11/11/14 by DW
2111 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2112 | getAllLists (function (theLists) {
2113 | httpResponse.end (utils.jsonStringify (theLists));
2114 | });
2115 | break;
2116 | case "/getonefeed": //11/26/14 by DW
2117 | var url = parsedUrl.query.url;
2118 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2119 | getOneFeed (url, function (theFeed) {
2120 | httpResponse.end (utils.jsonStringify (theFeed));
2121 | });
2122 | break;
2123 | case "/getoneriver": //11/28/14 by DW
2124 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2125 | getOneRiver (parsedUrl.query.fname, function (s) {
2126 | httpResponse.end (s);
2127 | });
2128 | break;
2129 | case "/getfeedmeta": //12/1/14 by DW -- for the list editor, just get the metadata about the feed
2130 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2131 | getFeedMetadata (parsedUrl.query.url, function (data) {
2132 | if (data == undefined) {
2133 | httpResponse.end ("");
2134 | }
2135 | else {
2136 | httpResponse.end (utils.jsonStringify (data));
2137 | }
2138 | });
2139 | break;
2140 | case "/readfile": //12/1/14 by DW
2141 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2142 | httpReadUrl (parsedUrl.query.url, function (s) {
2143 | if (s == undefined) {
2144 | httpResponse.end ("");
2145 | }
2146 | else {
2147 | httpResponse.end (s);
2148 | }
2149 | });
2150 | break;
2151 | case "/getprefs": //12/1/14 by DW
2152 | respondWithObject (serverData.prefs);
2153 | break;
2154 | case "/feedupdated": //6/4/15 by DW
2155 | var challenge = parsedUrl.query.challenge;
2156 | console.log ("/feedupdated: challenge == " + challenge);
2157 | httpResponse.writeHead (200, {"Content-Type": "text/plain"});
2158 | httpResponse.end (challenge);
2159 | break;
2160 | case "/favicon.ico": //7/19/15 by DW
2161 | httpResponse.writeHead (302, {"location": urlFavicon, "Content-Type": "text/plain"});
2162 | httpResponse.end ("302 REDIRECT");
2163 | break;
2164 | default: //404 not found
2165 | httpResponse.writeHead (404, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2166 | httpResponse.end ("\"" + lowerpath + "\" is not one of the endpoints defined by this server.");
2167 | }
2168 | break;
2169 | case "POST": //12/2/14 by DW
2170 | var body = "";
2171 | httpRequest.on ("data", function (data) {
2172 | body += data;
2173 | });
2174 | httpRequest.on ("end", function () {
2175 | var flPostAllowed = false;
2176 |
2177 | //set flPostAllowed -- 12/4/14 by DW
2178 | if (flLocalRequest) {
2179 | flPostAllowed = true;
2180 | }
2181 | else {
2182 | if (lowerpath == "/feedupdated") {
2183 | flPostAllowed = true;
2184 | }
2185 | else {
2186 | if (remotePassword.length > 0) { //must have password set
2187 | flPostAllowed = (parsedUrl.query.password === remotePassword);
2188 | }
2189 | }
2190 | }
2191 | if (flPostAllowed) {
2192 | console.log ("POST body length: " + body.length);
2193 | switch (lowerpath) {
2194 | case "/setprefs":
2195 | var newprefs = JSON.parse (body);
2196 | for (var x in newprefs) {
2197 | serverData.prefs [x] = newprefs [x];
2198 | }
2199 | saveServerData ();
2200 | respondWithObject ({});
2201 | break;
2202 | case "/savelist":
2203 | httpResponse.writeHead (200, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2204 | saveSubscriptionList (parsedUrl.query.listname, body);
2205 | httpResponse.end ("");
2206 | break;
2207 | case "/feedupdated": //6/4/15 by DW
2208 | var postbody = qs.parse (body);
2209 | rssCloudFeedUpdated (postbody.url);
2210 | httpResponse.writeHead (200, {"Content-Type": "text/plain"});
2211 | httpResponse.end ("Thanks for the update! :-)");
2212 | break;
2213 | default: //404 not found
2214 | httpResponse.writeHead (404, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2215 | httpResponse.end ("\"" + lowerpath + "\" is not one of the endpoints defined by this server.");
2216 | }
2217 | }
2218 | else {
2219 | httpResponse.writeHead (403, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2220 | httpResponse.end ("This feature can only be accessed locally.");
2221 | }
2222 | });
2223 | break;
2224 | }
2225 | }
2226 | catch (tryError) {
2227 | httpResponse.writeHead (503, {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"});
2228 | httpResponse.end (tryError.message);
2229 | }
2230 | }
2231 |
2232 | function loadConfig (callback) { //5/9/15 by DW
2233 | fs.readFile (fnameConfig, function (err, data) {
2234 | if (!err) {
2235 | var config = JSON.parse (data.toString ());
2236 | if (config.enabled !== undefined) {
2237 | flEnabled = utils.getBoolean (config.enabled);
2238 | }
2239 | if (config.fspath !== undefined) {
2240 | fspath = config.fspath;
2241 | }
2242 | if (config.password !== undefined) {
2243 | remotePassword = config.password;
2244 | }
2245 | if (config.s3path !== undefined) {
2246 | s3path = config.s3path;
2247 | }
2248 | if (config.PORT !== undefined) {
2249 | myPort = config.PORT;
2250 | }
2251 |
2252 | if (config.flWatchAppDateChange !== undefined) { //8/21/15 by DW
2253 | flWatchAppDateChange = utils.getBoolean (config.flWatchAppDateChange);
2254 | }
2255 | if (config.fnameApp !== undefined) { //8/21/15 by DW
2256 | fnameApp = config.fnameApp;
2257 | }
2258 |
2259 | if (config.s3defaultAcl !== s3defaultAcl) {
2260 | s3defaultAcl = config.s3defaultAcl;
2261 | }
2262 | appConfig = config; //6/4/15 by DW
2263 | }
2264 | if (callback !== undefined) {
2265 | callback ();
2266 | }
2267 | });
2268 | }
2269 |
2270 | function startup () {
2271 | if (process.env.s3defaultAcl !== undefined) { //7/19/14 by DW
2272 | s3defaultAcl = process.env.s3defaultAcl;
2273 | }
2274 | loadConfig (function () {
2275 | if ((s3path === undefined) && (fspath === undefined)) { //7/19/15 by DW
2276 | fspath = "river4data/";
2277 | }
2278 | if (fspath !== undefined) { //9/24/14 by DW
2279 | s3path = fspath;
2280 | }
2281 | //display startup message
2282 | var pathmsg = (fspath === undefined) ? ("s3 path == " + s3path) : ("file path == " + fspath);
2283 | console.log ("\n" + myProductName + " v" + myVersion + " running on port " + myPort + ", " + pathmsg);
2284 | if (remotePassword === undefined) { //12/4/14 by DW
2285 | remotePassword = "";
2286 | }
2287 | s3UserListsPath = s3path + "lists/"; //where users store their lists
2288 | s3UserRiversPath = s3path + "rivers/"; //where we store their rivers
2289 | s3PrefsAndStatsPath = s3path + "data/prefsAndStats.json";
2290 | s3LocalStoragePath = s3path + "data/localStorage.json"; //6/22/15 by DW
2291 | s3FeedsArrayPath = s3path + "data/feedsStats.json";
2292 | s3RiversArrayPath = s3path + "data/riversArray.json";
2293 | s3FeedsInListsPath = s3path + "data/feedsInLists.json";
2294 | s3FeedsDataFolder = s3path + "data/feeds/";
2295 | s3CalendarDataFolder = s3path + "data/calendar/";
2296 | s3BackupsFolder = s3path + "data/backups/"; //12/4/14 by DW
2297 | s3ListsDataFolder = s3path + "data/lists/";
2298 | s3IndexFile = s3path + "index.html";
2299 |
2300 | getAppModDate (function (appModDate) { //set origAppModDate -- 8/21/15 by DW
2301 | origAppModDate = appModDate;
2302 | loadServerData (function () {
2303 | applyPrefs ();
2304 |
2305 |
2306 | saveServerData (); //so hours-server-up stats update immediately
2307 |
2308 | loadFeedsArray (function () {
2309 | loadLocalStorage (function () { //6/20/15 by DW
2310 | loadTodaysRiver (function () {
2311 | loadListsFromFolder (); //adds tasks to the queue
2312 | //make sure all the top level folders are created -- 7/19/15 by DW
2313 | if (fspath !== undefined) {
2314 | fsSureFilePath (s3UserRiversPath, function () {
2315 | fsSureFilePath (s3UserListsPath, function () {
2316 | });
2317 | });
2318 | }
2319 | http.createServer (handleRequest).listen (myPort);
2320 | setInterval (everyQuarterSecond, 250);
2321 | setInterval (everySecond, 1000);
2322 | everyMinute (); //do one immediately on startup
2323 | });
2324 | });
2325 | });
2326 | });
2327 | });
2328 | });
2329 | }
2330 |
2331 | startup ();
2332 |
--------------------------------------------------------------------------------