notepad

Check-in [7d0372d469]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Initial code-up; Python CGI, sqlite3, no jquery
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | master | trunk
Files: files | file ages | folders
SHA3-256:7d0372d469b210f18eb94e6e7dd51ab7c3629d0edae9b4312d0171aa04cca2df
User & Date: vandys 2018-10-11 22:04:21
Context
2018-10-11
22:05
Clean "fs extras" check-in: d10f9fd4be user: vandys tags: master, trunk
22:04
Initial code-up; Python CGI, sqlite3, no jquery check-in: 7d0372d469 user: vandys tags: master, trunk
13:07
Split out CSS check-in: 9d44661392 user: vandys tags: master, trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to README.txt.

1
2
3


4
5
6
7
8
9
10
11
12
13
14
HTML5 Notepad App
by Kaspars Dambis
http://konstruktors.com



Installation
============

1. Upload files to your server
2. Rename 'entries' folder to something random and harder to guess
3. Make that folder writable (CHMOD 0777)
4. Edit sync.php and specify your new DATA_DIR (the one you just renamed)
5. In sync.php change username and password to something unique
6. Done!




>
>











1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HTML5 Notepad App
by Kaspars Dambis
http://konstruktors.com

<!-- Could Pad HTML5 App by Kaspars Dambis / http://konstruktors.com/cloud-notepad-html5 -->

Installation
============

1. Upload files to your server
2. Rename 'entries' folder to something random and harder to guess
3. Make that folder writable (CHMOD 0777)
4. Edit sync.php and specify your new DATA_DIR (the one you just renamed)
5. In sync.php change username and password to something unique
6. Done!

Deleted cache.manifest.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php header('Content-Type: text/cache-manifest'); ?>
CACHE MANIFEST
# v20121

CACHE:
index.html
images/icon-doc.png
js/jquery.min.js
js/wysiwym/wysiwym.js
js/wysiwym/wysiwym.css
js/wysiwym/buttons.light.png
js/coreyti-showdown/showdown.js
js/pretty.js

NETWORK:
sync.php
logout.php
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































Changes to css/main.css.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

	<style>	
		body { font:16px/1.5 arial; background:#eee; margin:0; padding:2em 0; }
		a { text-decoration:none; color:#666; }
		a:hover { color:#000; }
		#entries { position:fixed; padding:1em 0 0 0; left:0; bottom:0; top:1em; float:left; width:100%; }
		#entries nav { margin-top:1em; border-top:1px solid #ddd; }
		#entries a.edit { margin-right:-100em; border-bottom:1px solid #ddd; padding-left:2em; }
		#entries li { position:relative; }
		#entries li:hover { background:#ddd; }
		#entries a.edit:before { content:''; margin:0 -10em -10em -1.3em; display:block; float:left; width:20px; height:13px; background:url('images/icon-doc.png') no-repeat top left; }
		#entries time { float:right; position:absolute; top:0.9em; right:4em; font-size:13px; color:#999; }
		nav ul, nav li { line-height:1.2; display:block; margin:0; padding:0; position:relative; }
		nav a { display:block; padding:0.6em 1em 0.6em 1em; }
		#editor-wrap { display:block; display:block; }
		form {  margin:0 auto; padding:1em 2em; display:none; position:absolute; top:1.9em; left:0; bottom:0; right:0; }
		form input.title { font-family:inherit; font-weight:bold; width:inherit; outline:none; background:transparent; color:#000; border:1px dotted transparent; padding:5px 18px; margin:0; font-size:1em; position:absolute; top:1.3em; left:0; right:0; }
		textarea { width:inherit; color:#333; background:transparent; font:12px/1.6 'Monaco', 'Lucida Console', monospace; outline:none; display:block; margin:0; padding:15px; position:absolute; left:0; right:0; bottom:0; top:35px; border:none; }
		textarea { max-width:580px; } 
		nav a.delete { color:#666; background:#fff; display:none; position:absolute; padding:0.5em; right:1em; top:0.4em; -moz-border-radius:1em; -webkit-border-radius:1em; width:0.6em; height:0.6em; line-height:0.5; text-align:center; }
		nav a.delete:hover { background:#fff; }
		nav li:hover a.delete { display:block; }
		#tools { padding:0.5em 0; position:fixed; line-height:1; top:0; right:0; left:0; z-index:10; }
		#tools a { -webkit-border-radius:0.5em; display:block; float:left; padding:0.36em 0.8em; color:#fff; background:#ccc; text-shadow:none; }
		#tools a:focus { background:#000; }
		#tools a:hover { color:#fff; background:#333; text-shadow:none; }
		#tools li { float:left; margin-right:0.5em; display:block; list-style-type:none; }
		#tools nav { margin-left:0.5em; }
		#inform { display:none; position:fixed; width:10em; padding:0.5em; background:#333; color:#fff; z-index:50; top:0; left:50%; margin-left:-10em; font-size:1em; text-align:center; }
		#tools .clear-localstorage { float:right; }
		#tools #tool-new { float:right; }
		#tools #tool-save { display:none; position:absolute; left:9em; }
		#tools #tool-back { display:none; }
		#tools #tool-sync { float:right; }
		#tools #tool-logout { float:right; }
		#tools #tool-preview { display:none; }
		#credits { position:fixed; bottom:2em; right:2em; float:left; }
		#preview { display:none; position: absolute; z-index:50; padding:5px 10px; border:5px solid #ccc; top:0; left:0; right:0; background:#fff; min-height:70%; }
		#preview nav li { float:right; }
		#preview nav ul { float:right; margin-bottom:-10em; }
		#close-preview a {  }
	</style>

|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
1
2
3
4
5
6



































7
body>div {
    position: absolute;
    height: 100%;
    width: 100%;
    transition: all 2.0s ease;
    display: none;



































}

Deleted html5-notepad-app-chrome.zip.

cannot compute difference between binary files

Changes to index.html.

1
2

3
4
5
6
7
8
9
10

11
12
13
14

15

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36


37
38
39
40






41
42
43
44
45
46
47
48
49
50
51

52
53
54
55
56






57
58
59
60
61
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
<!DOCTYPE html>
<html lang="en" manifest="cache.manifest.php"> <!-- manifest="cache.manifest.php" --> 

<head>
	<title>Cloud Notepad</title>
	
	<meta charset="utf-8" />
	<!-- <meta http-equiv="pragma" content="no-cache" /> -->

	<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0" />
	<meta name="viewport" content="width=device-width" />   

    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    


</head>

<body>

<div id="wrap">
	<header id="tools">
		<nav>
			<ul>
				<li id="tool-back"><a href="#index" title="Back">Back</a></li>
				<li id="tool-new"><a href="#new" title="Add New">+</a></li>
				<li id="tool-sync"><a href="#" title="Sync Entries">Sync</a></li>
				<li id="tool-preview"><a href="#preview" title="Preview">Preview</a></li>
				<li id="tool-logout"><a href="#logout" title="Logout">Logout</a></li>
				<li class="clear-localstorage"><a href="#clear" id="clear" title="Clear localStorage">Clear</a></li>
			</ul>
		</nav>
	</header>
	
	<header id="entries">
		<nav>
			<ul><ul>
		</nav>
	</header>


	
	<section id="editor-wrap">
		<form name="editor" id="editor" method="post" action="">
			<input id="entry-id" type="hidden" name="entry-id" value="" />






			<textarea name="entry-content" id="entry-content" placeholder="Content"></textarea>
			<!-- <input type="submit" value="Save" /> -->
		</form>
	</section>
	
	<section id="inform"></section>

	<section id="preview">
		<nav>
			<ul>
				<li id="close-preview"><a href="#close-preview">Close</a></li>

			</ul>
		</nav>
		<div id="preview-content"></div>
	</section>







</div>


<script src="js/coreyti-showdown/showdown.js" type="text/javascript"></script>
<script src="js/pretty.js" type="text/javascript"></script>



<script type="text/javascript">
jQuery(document).ready(function($) {
	var $index = {};
	
	sync();

	$(window).bind('load hashchange', function () {
    	$('a[href="'+ window.location.hash +'"]').filter(':not(.delete)').trigger('click');
    	console.log($('a[href="'+ window.location.hash +'"]').filter(':not(.delete)'));
    	return false;
	});

	$('#entries a.edit').live('click', function(c) {
		//save_entry();
		var $id = $(this).attr('href').replace('#', '');
		var $item = $.parseJSON(localStorage.getItem($id));
		$.each($item, function(key, val) {
			$('#' + key).val(val);
  		});
		$('form').fadeIn();
		$('#tool-save, #tool-back, #tool-preview').show();
		$('#entries, #tool-new').hide();		
	});
	
	$('#entries a.delete').live('click', function(c) {
		if (confirm('Delete "' + $(this).siblings('a').text() + '"?') == true) {
			var $id = $(this).attr('href').replace('#', '');
			localStorage.removeItem($id);
			$index[$id] = { timestamp: 0 };
			localStorage.setItem('index', JSON.stringify($index));
			get_entries();
			if ($('#entry-id').val() == $id) { // we deleted the currently viewed item
				$('#entry-id').val('');
				$('#entry-content').val('');
			}
			sync();
		}
		return false;
	});
	
	$('#tool-new a').click(function(c) {
		$new_id = new Date().getTime() + '';
		$('#entry-id').val($new_id);
		$('#entry-content').val('');
		$('#tool-back').show();
		$('#entries').hide();
		$('form').fadeIn();
	});
	
	$('#tool-back a').click(function() {
		if (window.location.hash !== '#index')
			save_entry();
		get_entries();
		$('form, #tool-back, #tool-preview').hide();
		$('#tool-new, #entries').show();
	});
	
	$('#tool-sync a').click(function() {
		save_entry();
		sync();
	});
	
	var showdown = new Showdown.converter();

	$('#tool-preview a').click(function() {
		var preview_content = showdown.makeHtml($('textarea').val());
		$('#preview-content').html(preview_content);
		$('#preview').fadeIn();
	});
	
	$('#close-preview a').click(function(c) {
		c.preventDefault();
		$('#preview').hide();
	});
		
	$('input, textarea').blur(function() {
		$('form').submit();
	}).focus(function() {
		$('#tool-save').show();
	}).keyup(function(e) {
		if (e.keyCode == 32 || e.keyCode == 13) {
			$('form').submit();
		}
	});
	
	$('form').submit(function() {
		save_entry();
		get_entries();
		return false;
	});
	
	$('#tool-save').click(function(e) {
		e.preventDefault();
		$('form').submit();
		$(this).hide();
	});
	
	function save_entry() {
		var $id = $('#entry-id').val() + '';
		if ($id.length < 1)
			return;
		
		var $title = $('#entry-content').val() + '';
		var $timestamp = new Date().getTime() + ''; // make it a string
		
		$title = showdown.makeHtml($title);
		$title = $($title).text().split('\n\n')[0].substring(0, 20);

		$index[$id] = { timestamp: $timestamp, title: $title }; // set a new version number
		
		console.log('saved:');
		console.log($id);

		localStorage.setItem('index', JSON.stringify($index));
		localStorage.setItem($id, JSON.stringify($('form').formToJSON()));
	}
	
	function sync() {
		if (navigator.onLine) {
			// jquery doesn't know how to enumerate
			//  localStorage any more
			const ls = {};
			for (let i = 0; i < localStorage.length; ++i) {
			    const k = localStorage.key(i);
			    ls[k] = localStorage[k];
			}
			$.post('sync.php', ls, function(data) {
				console.log(data);
				localStorage.setItem('index', JSON.stringify(data.index));
				for (k in data.entries) {
					localStorage.setItem(k, JSON.stringify(data.entries[k]));
				}
				inform('Sync Completed!');
				console.log(localStorage);
				get_entries();
			}).error(function() { 
				inform('Sync error'); 
			});
		} else {
			inform("You are offline!");
			get_entries();
		}
	}

	$('#tool-logout a').click(function() {
		$.get('logout.php', null, function() {
			inform('Logout success!');
			$('#wrap').fadeOut('fast');
		}).error(function() { 
			inform('Logout error'); 
		});
		return false;
	});
	
	function get_entries() {
		$index = new Object(JSON.parse(localStorage.getItem('index')));
		if ($index.length < 1)
			$index = {};
		build_entries($index);
	}
	
	function build_entries(data) {
		var $items = [];
		if (data == null) {
			$('#entries ul').html('');
			return;
		}
		$.each(data, function(key, val) {
			var title = val['title'];
			//var timeago = new Date(parseInt(val['timestamp']));
			
			if (title === '')
				title = 'Untitled';
			if (val['timestamp'] !== 0)
				$items.push('<li class="e-' + key + '"><a class="edit" href="#' + key + '">' + title + '</a> <time></time> <a class="delete" href="#' + key + '">-</a></li>');
  		});
  		$('#entries ul').hide().html($items.reverse().join('')).show();
	}
	
	function inform($message) {
		console.log($message);
		$('#inform').html($message).stop().fadeIn().delay(1000).fadeOut('fast');
	}
	
	$('#clear').click(function() {
		localStorage.clear();
		get_entries();
	});

	$.fn.formToJSON = function() {
		var json = {};
		$.map($(this).serializeArray(), function(n, i){
			json[n['name']] = n['value'];
		});
		return json;
	};

});



</script>

<!-- Could Pad HTML5 App by Kaspars Dambis / http://konstruktors.com/cloud-notepad-html5 -->

</body>
</html>

|
>

|

|
|

|
<
>


<
<
>

>


|
|
<
|
|
|
|
<
<
<
|
<
<
|
|
<
<
<
<
>
>
|
|
<
<
>
>
>
>
>
>
|
<
<
<
<
<
<
<
<
<
<
>
|
<
<
<

>
>
>
>
>
>


<
<
|

>

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
>


<
<
<

1
2
3
4
5
6
7
8
9
10

11
12
13


14
15
16
17
18
19
20

21
22
23
24



25


26
27




28
29
30
31


32
33
34
35
36
37
38










39
40



41
42
43
44
45
46
47
48
49


50
51
52
53
54






































































































































































































55
56
57
58



59
<!DOCTYPE html>
<html lang="en" manifest="cache.manifest.php">
<!-- manifest="cache.manifest.php" --> 
<head>
    <title>Cloud Notepad</title>
	
    <meta charset="utf-8" />
    <!-- <meta http-equiv="pragma" content="no-cache" /> -->

    <meta name="viewport" content="user-scalable=no, width=device-width,

     initial-scale=1.0, maximum-scale=1.0" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />


    <link rel="stylesheet" type="text/css" href="css/main.css" />
</head>

<body>

<div id="mainmenu">
    <div id="tools">

	<span onclick="tool_new()">Add New</span>
	<span onclick="tool_sync()">Sync Entries</span>
	<span onclick="tool_logout()">Logout</span>
	<span onclick="tool_clear()">Clear Local Storage</span>



    </div>



    <div id="entries">




    </div>
</div>

<div id="editor">


    <div id="entryTitle"></div>
    <div>
	<span onclick="edit_keep()">Save</span>
	<span onclick="edit_cancel()">Cancel</span>
	<span onclick="edit_delete()">Delete This</span>
    </div>
    <textarea name="entry-content" id="entryContent"










     placeholder="Content"></textarea>
</div>




<div id="login">
    <input type="text" id="user" placeholder="User name">
    <br>
    <input type="password" id="password" placeholder="password">
    <br>
    <button onclick="try_login()">Login</button>
</div>



<script src="js/main.js">

</body>

<script>






































































































































































































// Hook for initial JS execution
document.onready = startup;
</script>




</html>

Added js/main.js.























































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
//
// main.js
//	Main app code for notepad
//
// localStorage is used extensively:
//
// Each item is under a key, with the fields:
//  key - Our key under localStorage (in the format "noteXXXX")
//  tm - Time item was last updated (value always used as float)
//  title - String name of this note
//  content - String contents of body of note
//
// localStorage.tm is the time (parsed as float) when we last
//  updated from the server.
//
"use strict";

// When a note selected and being viewed/edited
let cur_item = null;

// Last time value when updated from server
let server_tm = null;

// When we need to fake a timestamp to offer sequential, new
//  changes to our server when our own clock is borked.
let tm_off = 0.0;

// Try to pull in current store on startup
function startup() {
    if (localStorage.getItem("tm") == null) {
	// Initial state
	localStorage.tm = "0.0";
	server_tm = 0.0;
	// They need to log in
	login.style.display = "block";
    } else {
	// Saved state
	server_tm = parseFloat(localStorage.tm);
	to_menu();
    }
    sync();
}

// Mint a new key for a new note
function new_key() {
    while (true) {
	let key = "note" +
	    Math.floor(Math.random() * 1000000000.0).toString();
	if (localStorage.getItem(key) == null) {
	    return key;
	}
    }
}

// Transition to displaying an item
// (Switching to "display: none" side steps a bunch of grotty
//  details on z-index touch item priority.)
function to_item() {
    mainmenu.style.opacity = 0.0;
    setTimeout(() => {mainmenu.style.display = "none";}, 1000);
    editor.style.display = "block";
    editor.style.opacity = 1.0;
}

// Transition back to main menu
function to_menu() {
    editor.style.opacity = 0.0;
    setTimeout(() => {editor.style.display = "none";}, 1000);
    mainmenu.style.display = "block";
    mainmenu.style.opacity = 1.0;
}

// They've chosen from our list of items
function item_click(key) {
    cur_item = JSON.parse(localStorage(key));
    entryTitle.textContent = cur_item.title;
    entryContent.value = cur_item.content;
    to_item();
}

// Sort notes by their alphabetic title ordering
// (Maybe could order by tm/recentness instead?)
function cmpTitles(ent1, ent2) {
    if (ent1.title == ent2.title) {
	return 0;
    }
    if (ent1.title < ent2.title) {
	return -1;
    }
    return 1;
}

// Walk all notes, put them into our selectable list
function update_entries() {
    // Remove old list
    while (entries.hasChildNodes()) {
	entries.removeChild(entries.lastChild);
    }

    // Traverse localStorage, assemble notes
    ents = [];
    for (let idx = 0; idx < localStorage.length; ++idx) {
	let key = localStorage.key(idx);
	if (!key.startsWith("note")) {
	    // Ignore non-note state
	    continue;
	}

	let ent = JSON.parse(localStorage[key]);
	if (ent.title == null) {
	    // Deleted
	    continue;
	}

	ents.push(ent);
    }

    // Order by title
    ents.sort(cmpTitles);

    // Populate our list of notes
    ents.forEach( ent => {
	// Clickable span w. text
	let e = document.createElement("span");
	e.textContent = ent.title;
	e.onclick = () => { item_click(ent.key); };
	entries.appendChild(e);
    });
}

// Update timestamp on our storage, because we've changed something
// Return the updated value as a float
function timestamp() {
    let tm = Date().getTime();
    if (tm <= (server_tm + tm_off)) {
	// Synthesize a time offset when our own clock doesn't
	//  line up (for whatever reason) with the server's
	tm_off += 0.1;
	tm = server_tm + tm_off;
    }
    return tm;
}

// The current item should Go Away
function edit_delete() {
    // Defend against fat finger
    if (!confirm("Delete " + entryTitle.textContent) + "?") {
	return;
    }

    // Storage gone, replace entry with time of deletion and null
    //  title (as a way to flag a deleted entry)
    const tm = timestamp();
    const resp = {"key": cur_item.key,
	"tm": tm, "title": null, "content": null};
    localstorage[cur_item.key] = JSON.stringify(resp);
    cur_item = null;

    // Maybe get word to the server
    sync();

    // Update item list
    update_entries();

    // Back to menu
    to_menu();
}

// Never mind, dump any changes
function edit_cancel() {
    // Double check?
    if (entryContent.value != cur_item.content) {
	if (!confirm("Discard changes?")) {
	    return;
	}
    }

    // Back to main menu
    to_menu();
}

// Update content and timestamp for this note
function edit_keep() {
    cur_item.content = entrycontent.value;
    cur_item.tm = timestamp();
    sync();
    udpate_entries();
    to_menu();
}

// Create a delta of changes, so we only have to submit back things
//  which have changed WRT our last update from the server
function save_notes() {
    const upd = {}
    for (let idx = 0; idx < localStorage.length; ++idx) {
	let key = localStorage.key(idx);
	if (key.startsWith("note")) {
	    let ent = JSON.parse(localStorage[key]);
	    if (ent.tm > server_tm) {
		upd[key] = ent;
	    }
	}
    }
    return upd;
}

// Server has handed back deltas to let us catch up
function update_notes(deltas) {
    // Record time at which we caught up
    server_tm = parseFloat(deltas.tm);
    localStorage.tm = server_tm.toString();
    tm_off = 0.0;

    // Each note which has something interesting
    for (let key in deltas) {
	if (!key.startsWith("note")) {
	    continue;
	}
	let ent = deltas[key];
	if (ent.title == null) {
	    // Deleted note
	    delete localStorage[key];
	} else {
	    // New or updated note
	    localStorage[key] = JSON.stringify(ent);
	}
    }
}

// Hand our current idea of notes to the server, get back
//  a reconciliation with possible changes from other devices.
function sync() {
    if (!navigator.onLine) {
	alert("No network access");
	return;
    }
    const req = new XMLHttpRequest();
    req.open("POST", "sync.py");
    req.onreadystatechange = () => {
	if (req.readyState != 4) {
	    return;
	}
	if (req.status != 200) {
	    alert("Sync error");
	    return;
	}

	// Here's a refreshed notion of note content
	const deltas = JSON.parse(req.responseText);
	update_notes(deltas);
	update_entries();
    }

    // Submit our current content, including credentials
    const onotes = save_notes();
    onotes.user = user.value;
    onotes.password = password.value;
    req.send(JSON.stringify(onotes));
}

// Log out (clear localStorage and PHP server side)
function tool_logout() {
    if (!confirm("Clear notes session?")) {
	return;
    }
    localStorage.clear();
    location.reload();
}

// Initial setup, try to log in
function try_login() {
    if (!user.value) {
	alert("Please enter your user name");
	return;
    }
    if (!password.value) {
	alert("Please enter your password");
	return;
    }
    const creds = {"user": user.value, "password": password.value};
    const req = new XMLHttpRequest();
    req.open("POST", "login.py");
    req.onreadystatechange = () => {
	if (req.readyState != 4) {
	    return;
	}
	if (req.status != 200) {
	    alert("Login failed, try again");
	    return;
	}

	// User/pass is OK, so go to main UI
	login.style.display = "none";
	to_menu();
    }

    // Submit our current content
    req.send(JSON.stringify(creds));
}

Deleted logout.php.

1
2
3
4
<?php 
	unset($_SERVER['PHP_AUTH_USER']);
	unset($_SERVER['PHP_AUTH_PWD']);
?>
<
<
<
<








Added mkdb.sql.

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
create table accounts(
    user varchar primary key,
    password varchar
);
create table notes(
    key varchar,
    user varchar,
    tm real,
    title varchar,
    content varchar,
    unique(key, user)
);

Deleted sync.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?php

error_reporting(E_ERROR);

define('DATA_DIR', 'entries'); // use this to protect files from being publicly viewable
define("USERNAME", 'demo');
define('PASSWORD', 'demo');

if (($_SERVER['PHP_AUTH_USER'] !== USERNAME) || ($_SERVER['PHP_AUTH_PW'] !== PASSWORD)) {
    header('WWW-Authenticate: Basic realm="Cloud Notes"');
    header('HTTP/1.0 401 Unauthorized');
    exit;
}

header('Content-type: application/json; charset=utf-8');
	
// Parse incoming data

$remote_index = (array)json_decode(stripslashes($_POST['index']), true);
unset($_POST['index']);
$remote_entries = $_POST;

// Process

$local_index = get_entry('_index');

$diff_index = array_diff_key($local_index, $remote_index);

$debug = array();

$debug['new entries'] = $remote_entries;
$debug['old entries'] = get_entries();


foreach ($remote_index as $id => $item) {
	if (array_key_exists($id, $local_index)) {
		if ($item['timestamp'] == 0) {
			// Remote entry has been deleted, remove the local too
			$local_index[$id] = $item;
			delete_entry($id);
			unset($remote_index[$id]);
			unset($remote_entries[$id]);
		} elseif ($local_index[$id]['timestamp'] == 0) {
			// Local entry has been deleted, remove local entry too
			$remote_index[$id] = $local_index[$id];
			delete_entry($id);
			unset($remote_index[$id]);
			unset($remote_entries[$id]);
		} elseif ($item['timestamp'] > $local_index[$id]['timestamp']) {
			// Remote entry is newer, replace it and don't send it back
			$local_index[$id] = $item;
			store_entry($id, $_POST[$id]);
			unset($remote_entries[$id]);
			unset($local_entries[$id]);
		} elseif ($item['timestamp'] == $local_index[$id]['timestamp']) {
			// Local entry is already the latest, don't send it back
			unset($remote_entries[$id]);
			unset($local_entries[$id]);
		} else {
			// Local entry is newer, send it back
			$remote_index[$id] = $local_index[$id];
			$remote_entries[$id] = get_entry($id);
		}
	} else {
		$local_index[$id] = $remote_index[$id];
		store_entry($id, $_POST[$id]);
		unset($remote_entries[$id]);
	}
}

foreach ($diff_index as $id => $data) {
	//echo $data['timestamp'];
	if ($local_index[$id]['timestamp'] !== 0) {
		$remote_entries[$id] = get_entry($id);
		$remote_index[$id] = $local_index[$id];
	} else {
		unset($remote_entries[$id]);
		unset($remote_index[$id]);
	}
}

store_entry('_index', $local_index);

$return = array('index' => $remote_index, 'entries' => $remote_entries, 'debug' => $debug);
echo json_encode($return);


// Helpers

function get_entry($id) {
	$file = DATA_DIR . '/' . $id;
	if (file_exists($file)) {
		if ($le = json_decode(file_get_contents($file), true)) {
			return $le; // return addslashes($le);
		}
	}
	return array();
}

function store_entry($id, $data) {
	$file = DATA_DIR . '/' . $id;
	if (empty($data))
		return;
	if (is_array($data))
		$data = json_encode($data);
	
	// $data = stripslashes($data);

	file_put_contents($file, $data) 
		or die_json("Can't read the file!");
}

function delete_entry($id) {
	$file = DATA_DIR . '/' . $id;
	if (file_exists($file))
		unlink($file);
}

function die_json($message) {
	echo json_encode(array('error' => $message));
	exit;
}

function get_entries() {
	$entries = array();
	if ($handle = opendir(DATA_DIR)) {
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != "..") {
				$entry = json_decode(file_get_contents(DATA_DIR . '/' . $file), true);
				$entries[$file] = $entry;
			}
		}
		closedir($handle);
	}
	if (!empty($entries))
		return json_encode($entries);
}

?>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































Added sync.py.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/python
#
# sync.py
#	Accept POST of new entries to our note DB
#
import cgi, sys, json, time
import sqlite3
w = sys.stdout.write

# Connect to DB
# (Use a name which outsiders won't know.)
conn = sqlite3.connect("notes-4323zz.db")

# This is a JSON API
w("Content-Type: application/json\n")

# Say we can't grok it & bail
tm1 = hours1 = tm2 = sel = None
def fail(msg):
    w("Status: 400 Bad Request\n\n%s" % (json.dumps({"err": msg}),))
    sys.exit(0)

# Parse CGI header
cgi.maxlen = 128*1024
fields = cgi.parse()

# JSON body
try:
    req = json.load(sys.stdin)
    tm = float(req["tm"])
    if tm < 0.0:
	raise Exception
except:
    fail("Bad JSON input")

# Logged in?
user = str(req.get("user", ""))
pw = str(req.get("password", ""))
if (not user) or (not pw):
    fail("Bad login credentials")

# Verify pw
c = conn.cursor()
c.execute("select password from accounts where user=?", (user,))
tup = c.fetchone()
c.close()
if (tup is None) or (tup[0] != pw):
    fail("Bad login")

# Gather our current notes, keyed by note's index name (noteXXXX)
onotes = {}
c = conn.cursor()
c.execute(
 "select key,tm,title,content from notes where user=? and tm>?",
 (user, tm))
for tup in c:
    onotes[tup[0]] = {"tm": tup[1], "title": tup[2], "content": tup[3])

# For each note which they've changed, either accept the change,
#  or send back the newer content which we've already received.
resp = {}
changes = False
c = conn.cursor()
for key,note in req.iteritems():
    # Only notes
    if not key.startswith("note"):
	continue

    # Nothing newer, so just register note
    # (This includes deleted notes, which are like others with
    #  key/timestamp, but with title/content being null.)
    oent = onotes.get(key)
    if oent is None:
	c.execute("insert into notes values=(?,?,?,?)",
	    (key, note["tm"], note["title"], note["content"]))
	changes = True
	continue

    # We both have updates, but server already has newest.
    # Include this value in the response update back.
    if oent["tm"] > note["tm"]:
	resp[key] = oent
	continue

    # We have something new-ish, but theirs is newer yet.
    # Go with it.
    c.execute(
     "update notes set tm=?, title=?, content=? where key=?",
     (note["tm"], note["title"], note["content"], key))
    changes = True

# Now we need to fold in new stuff from our own DB
for key,note in onotes.iteritems():
    # Already processed in previous loop
    if key in req:
	continue

    # Ok, tell them about it
    resp[key] = note
    changes = True

# Commit DB changes
if changes:
    conn.commit()
conn.close()

# Give them an update including time
resp["tm"] = time.time()
w(json.dumps(resp))

sys.exit(0)