-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain1.0.js
More file actions
478 lines (461 loc) · 22.9 KB
/
main1.0.js
File metadata and controls
478 lines (461 loc) · 22.9 KB
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/*jshint esversion: 6 */
$("#actionspanelcustomer").hide();
$("#actionspanelartist").hide();
$("#actionspanelstatistic").hide();
var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8545/')); //<-- for local blockchian (Ganache) or for Geth
//var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); // <-- for Parity node (Ropsten)
var CatalogSmartContract;
var followingArtists = [];
var followingGenres = [];
web3.eth.getAccounts()
.then(function (data) {
console.log(data);
web3.eth.defaultAccount = data[8];
$("#current-eth-address").text("Hi! Your ETH address is " + web3.eth.defaultAccount);
return web3.eth.getBalance(web3.eth.defaultAccount);
})
.then(function (balance) {
$("#current-eth-balance").text(" with balance " + web3.utils.fromWei(balance, 'ether') + " Ether");
if (web3.currentProvider.host != undefined) {
$("#current-eth-place").text("on : " + web3.currentProvider.host);
}
CatalogSmartContract = new web3.eth.Contract(abiCatalog, catalogAddress);
console.log(CatalogSmartContract);
return CatalogSmartContract.methods.isPremium(web3.eth.defaultAccount)
.call();
})
.then(function (isPremium) {
$("#actionspanelcustomer").show();
$("#actionspanelartist").show();
$("#actionspanelstatistic").show();
$("#loginpanel").css('background-color', '#C8E6C9');
setUpEvents(isPremium);
setUpUI(isPremium);
})
.catch(function (err) {
console.log(err);
$("#loginpanel").attr("class", "card text-white bg-danger mb-3");
$("#loginpanel").append("<h3 class='card-text'>" + err.toString() + "<\h3>");
});
function setUpUI(isPremium) {
var contractFileSelected;
//Setting up Buttons action
//Button action for Artist Panel
$("#inputfile").on('change', function (file) {
contractFileSelected = $('#inputfile').prop('files')[0];
});
$("#buttontopublishcontent").click(function () {
//parse input
let name = $("#namecontenttopublish").val();
let genre = $("#genrecontent").val();
let artist = $("#artistname").val();
if (name == "" || genre == "" || artist == "" || contractFileSelected == null) {
displayErrorAfterButton("publishpanel", "Please insert name, genre, your artist name and select the compliled contract");
}
else {
let namebyte = web3.utils.asciiToHex(name);
let genrebytes = web3.utils.asciiToHex(genre);
let priceint = Number(web3.utils.toWei($("#pricecontent").val(), 'ether'));
let artistnamebyte = web3.utils.asciiToHex(artist);
console.log(contractFileSelected);
let fr = new FileReader();
fr.onload = function (result) {
let jsonContract = JSON.parse(result.target.result);
console.log(jsonContract);
//name of the json file have o be the name of the Contract, in a different file of ContentManager
let nameContract = contractFileSelected.name.slice(0, -5);
let nameInJson = nameContract + ".sol:" + nameContract;
let abi = JSON.parse(jsonContract.contracts[nameInJson].abi);
let code = '0x' + jsonContract.contracts[nameInJson].bin;
console.log("Deploying the contract");
let myContract = new web3.eth.Contract(abi, { gas: 3000000, gasPrice: '2000000000', from: web3.eth.defaultAccount });
console.log(myContract);
return myContract
.deploy({ data: code, arguments: [namebyte, genrebytes, priceint, artistnamebyte, catalogAddress] })
.send()
.then(function (newContractInstance) {
console.log(newContractInstance);
return CatalogSmartContract.methods.NewContent(newContractInstance.options.address)
.send({ gas: 3000000, from: web3.eth.defaultAccount });
})
.then(function () {
console.log("Ok");
alert("Content " + name + " published!");
$("#namecontenttopublish").val("");
$("#genrecontent").val("");
$("#artistname").val("");
$("#pricecontent").val("0.01");
})
.catch(function (err) {
console.log(err);
displayErrorAfterButton("publishpanel", "Something goes wrong. Maybe you choose a name of content that already exist, or you choose a author name that already exist ");
});
};
fr.readAsText(contractFileSelected);
}
});
// Buttons for gifts
$("#buttontogiftcontent").click(function () {
let namebytes = web3.utils.asciiToHex($("#namecontentgift").val());
let address = $("#namerecipient").val();
if (web3.utils.isAddress(address)) {
CatalogSmartContract.methods.isPremium(address)
.call()
.then(function (isPremium) {
if (!isPremium) {
CatalogSmartContract.methods.getPriceContent(namebytes)
.call()
.then(function (price) {
if (window.confirm("You are gifting a content to " + address + ". Buying this content costs " + web3.utils.fromWei(price, 'ether') + " ether. Do you agree?")) {
CatalogSmartContract.methods.GiftContent(namebytes, address)
.send({ value: price, gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount })
.then(function (result) {
alert("Gifted!");
console.log(result);
});
}
})
.catch(function (err) {
displayErrorInForm("namecontentgift", "This content doesn't exist.");
console.log(err);
});
}
else {
displayErrorInForm("namerecipient", "Customer " + address + " is premium. He already has access to all content.");
}
})
.catch(err => console.log(err));
} else {
displayErrorInForm("namerecipient", "Invalid Address.");
}
});
$("#buttontogiftpremium").click(function () {
let address = $("#namerecipientaddress").val();
if (web3.utils.isAddress(address)) {
CatalogSmartContract.methods.isPremium(address)
.call()
.then(function (isPremium) {
if (!isPremium) {
if (window.confirm("You are gifting a premium account to " + address + ". Buying premium costs 1 ether. Do you agree?")) {
CatalogSmartContract.methods.GiftPremium(address)
.send({ value: web3.utils.toWei("1", "ether"), gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount })
.then(function (result) {
alert("Gifted!");
console.log(result);
});
}
}
else {
displayErrorInForm("namerecipientaddress", "Customer " + address + " is premium. He already has access to all content.");
}
})
.catch(err => console.log(err));
} else {
displayErrorInForm("namerecipientaddress", "Invalid Address.");
}
});
// Buttons action for Statistic panel
$("#buttontogetstatisticsviws").click(function () {
var contentList;
CatalogSmartContract.methods.GetContentList()
.call()
.then(function (result) {
contentList = result;
})
.then(function () {
return CatalogSmartContract.methods.GetStatistics()
.call();
}).then(function (result) {
var totalstring = "";
for (var i = 0; i < contentList.length; i++) {
let namestring = web3.utils.hexToAscii(contentList[i]);
console.log(namestring + " views = " + result[i]);
totalstring += (namestring + " views = " + result[i] + "\n");
}
alert("Result : \n" + totalstring);
})
.catch(err => console.log(err));
});
$("#buttontogetstatisticscontentlist").click(function () {
CatalogSmartContract.methods.GetContentList()
.call()
.then(function (result) {
var totalstring = "";
for (var i = 0; i < result.length; i++) {
let namestring = web3.utils.hexToAscii(result[i]);
totalstring += (namestring + "\n");
}
alert("Result : \n" + totalstring);
})
.catch(err => console.log(err));
});
$("#buttontogetfeedbacks").click(function () {
var contentList;
CatalogSmartContract.methods.GetContentList()
.call()
.then(function (result) {
contentList = result;
});
console.log($("#feedbacktoget").prop('selectedIndex'));
let selectedIndex = $("#feedbacktoget").prop('selectedIndex');
if (selectedIndex == 0) {
CatalogSmartContract.methods.GetFeedBacks()
.call()
.then(function (result) {
var totalstring = "";
for (var i = 0; i < contentList.length; i++) {
let namestring = web3.utils.hexToAscii(contentList[i]);
console.log(namestring + " views = " + result[i] + " " + (result[i] / 1000));
totalstring += (namestring + " all feedback mean = " + result[i] / 1000 + "\n");
}
alert("Result : \n" + totalstring);
return;
})
.catch(err => console.log(err));
}
if (selectedIndex >= 1 && selectedIndex <= 3) {
CatalogSmartContract.methods.GetMeanFeedBackCategory(selectedIndex)
.call()
.then(function (result) {
var totalstring = "";
for (var i = 0; i < contentList.length; i++) {
let namestring = web3.utils.hexToAscii(contentList[i]);
console.log(namestring + " views = " + result[i] + " " + (result[i] / 1000));
totalstring += (namestring + " 'Appreciation of the content' feedback mean = " + result[i] / 1000 + "\n");
}
alert("Result : \n" + totalstring);
return;
})
.catch(err => console.log(err));
}
});
// Button action for notification
$("#buttontonotify").click(function () {
let name = $("#nameauthornotify").val();
let genre_ = $("#namegenrenotify").val();
if (name == "" && genre_ == "") {
displayErrorAfterButton("notifypanel", "Please insert a name of Author o a Genre");
}
else {
if (name != "") {
alert("Subscribed to content published by " + name);
followingArtists.push(name);
}
if (genre_ != "") {
alert("Subscribed to content of genre " + genre_);
followingGenres.push(genre_);
}
}
});
// Button action for leave a feedback
$("#buttontofeedback").click(function () {
let content = $("#namefeedback").val();
if (content == "") {
displayErrorAfterButton("feedbackpanel", "Please select wich content you want to feedback");
}
else {
let f1 = $("#feedback1").val();
let f2 = $("#feedback2").val();
let f3 = $("#feedback3").val();
console.log(f1, f2, f3);
let contentbytes = web3.utils.asciiToHex(content);
CatalogSmartContract.methods.getAddressContent(contentbytes)
.call()
.then(function (address) {
let ContentManagementContract = new web3.eth.Contract(abiContent, address);
if (isPremium) {
return ContentManagementContract.methods.LeaveFeedBackPremium(f1, f2, f3)
.send({ value: 0, gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount });
}
else {
return ContentManagementContract.methods.LeaveFeedBackStandard(f1, f2, f3)
.send({ value: 0, gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount });
}
})
.then(function (transaction) {
console.log(transaction);
alert("Feedback sent! Thank's!");
})
.catch(function (err) {
console.log(err);
displayErrorAfterButton("feedbackpanel", "Error sending feedback, have you consumed this content?");
});
}
});
if (isPremium) {
//Button action for Premium customer
console.log("Setting up premium ui");
$("#loginpanel").append("<div class='card-body text-success'> <div class='card-header'> <h5 class='card-title'>Logged as Premium Account</h5> </div> </div> ");
$("#buttontogetaccesscontent").click(function () {
let namecontent = $("#namecontent").val();
let namecontentbytes = web3.utils.asciiToHex(namecontent);
CatalogSmartContract.methods.GetContentPremium(namecontentbytes)
.send({ value: 0, gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount })
.then(function (result) {
alert("Now you can consume content : " + namecontent);
})
.catch(function (err) {
console.log(err);
displayErrorInForm("namecontent", "Error, are you sure this content exists? Are you already premium? Refresh the page to check");
});
});
$("#buttontogetcontent").click(function () {
let namecontent = $("#namecontentconsume").val();
let namebytes = web3.utils.asciiToHex(namecontent);
CatalogSmartContract.methods.getAddressContent(namebytes)
.call()
.then(function (address) {
console.log(address);
let ContentManagementContract = new web3.eth.Contract(abiContent, address);
return ContentManagementContract.methods.retriveContentPremium()
.send({ value: 0, gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount });
})
.then(function (transaction) {
alert(namecontent + " consumed.");
console.log("Content obtained.");
})
.catch(function (err) {
displayErrorAfterButton("getpanelpanel", "Are you sure you are already premium? Realod the page");
console.log(err);
});
});
}
else {
//Button action for Standard customer
console.log("Setting up standard ui");
$("#loginpanel").append("<div id='cardbobystandard' class='card-body text-success'> <div class='card-header' style='background-color:#C8E6C9'> <h5 class='card-title'>Logged as Standard Account</h5> </div> </div> <div class='card-body'> <button id='buttonforpremium' type='button' class='btn btn-outline-success'>Get Premium Account (1 ETH) </button> <\div>");
$("#buttonforpremium").click(function () {
if (window.confirm("Buying premium costs 1 ether. Do you agree?")) {
CatalogSmartContract.methods.BuyPremium().send({ from: web3.eth.defaultAccount, value: web3.utils.toWei("1", "ether") })
.then(function (transaction) {
alert("Payed 1 Ether! Transaction hash = " + transaction.transactionHash);
console.log(transaction);
location.reload();
})
.catch(function (err) {
console.log(err);
$("#loginpanel").append("<div style='color: #ff0000' >Error, are you sure you have the rigth ammount of Ether?</div>");
displayErrorAfterButton("loginpanel", "Error, are you sure you have the rigth ammount of Ether?");
});
}
});
$("#buttontogetaccesscontent").click(function () {
let namecontent = $("#namecontent").val();
let namecontentbytes = web3.utils.asciiToHex(namecontent);
CatalogSmartContract.methods.getPriceContent(namecontentbytes)
.call()
.then(function (price) {
if (window.confirm("Buying this content costs " + web3.utils.fromWei(price, 'ether') + " ether. Do you agree?")) {
CatalogSmartContract.methods.GetContent(namecontentbytes)
.send({ value: price, gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount })
.then(function (transaction) {
console.log(transaction);
console.log("obtained access");
alert("Payed " + web3.utils.fromWei(price, 'ether') + " Ether! Transaction hash = " + transaction.transactionHash);
});
}
})
.catch(function (err) {
console.log(err);
displayErrorInForm("namecontent", "Error, are you sure this content exists or you have the rigth ammount of Ether?");
});
});
$("#buttontogetcontent").click(function () {
let name = $("#namecontentconsume").val();
let namebytes = web3.utils.asciiToHex(name);
CatalogSmartContract.methods.getAddressContent(namebytes)
.call()
.then(function (address) {
let ContentManagementContract = new web3.eth.Contract(abiContent, address);
console.log("address of the content : ");
console.log(address);
return ContentManagementContract.methods.retriveContentStandard()
.send({ value: 0, gas: 1500000, gasPrice: '2000000000', from: web3.eth.defaultAccount });
})
.then(function (transaction) {
alert(name + " consumed.");
alert("Now you can leave a feedback for this content. At the bottom of this page you can find the right form to do it.");
console.log("Content obtained.");
})
.catch(function (err) {
console.log(err);
displayErrorInForm("namecontentconsume", "Error, are you sure you have rigth to access this content?");
});
});
}
}
function setUpEvents(isPremium) {
//For notification
//Setting up events
if (!isPremium) {
CatalogSmartContract.events.ContentAccessGifted()
.on('data', function (event) {
if (event.returnValues.to.localeCompare(web3.eth.defaultAccount) == 0) {
alert("NOTIFICATION: " + event.returnValues.from + " gifted you content: " + web3.utils.hexToAscii(event.returnValues.name) + "!");
}
})
.on('error', console.error);
CatalogSmartContract.events.PremiumGifted()
.on('data', function (event) {
if (event.returnValues.to.localeCompare(web3.eth.defaultAccount) == 0) {
alert("NOTIFICATION: " + event.returnValues.from + " gifted you a Premium account!");
location.reload();
}
})
.on('error', console.error);
}
CatalogSmartContract.events.NewContentEvent()//{
//filter: { autor: nameauthor } , <- doesn't work (web3 1.0.0 beta 33) so I did it by myself
//}
.on('data', function (event) {
for (let i = 0; i < followingGenres.length; i++) {
if (web3.utils.hexToAscii(event.returnValues.genre).localeCompare(followingGenres[i]) == 0) {
alert("NOTIFICATION: New content published of genre " + followingGenres[i]);
}
}
for (let i = 0; i < followingArtists.length; i++) {
if (web3.utils.hexToAscii(event.returnValues.autor).localeCompare(followingArtists[i]) == 0) {
alert("NOTIFICATION: New content published from " + followingArtists[i]);
}
}
})
.on('error', console.error);
//debug not userfull for the Dapp
$("#close").click(function () {
CatalogSmartContract.methods.close()
.send({ from: web3.eth.defaultAccount })
.then(function (result) {
console.log(result);
alert("COBrA Dapp is now closed! :(");
})
.catch(function (err) {
console.log(err);
alert("Only catalog owner can close the COBrA Dapp!");
});
});
}
function displayErrorInForm(idElement, stringToAdd) {
if ($("#" + idElement).next().is(".invalid-feedback")) {
$("#" + idElement).next().remove();
}
let newid = Math.floor(Math.random() * 100);
$("#" + idElement).attr("class", "form-control is-invalid");
$("#" + idElement).after("<div id='" + newid + "' class='invalid-feedback'>" + stringToAdd + "</div>");
setTimeout(function () {
if ($('#' + newid + '').length > 0) {
$('#' + newid + '').remove();
}
}, 5000);
}
function displayErrorAfterButton(idElement, stringToAdd) {
if ($("#" + idElement).children().last().attr("class") == undefined) {
$("#" + idElement).children().last().remove();
}
let newid = Math.floor(Math.random() * 100);
$("#" + idElement).append("<div id='" + newid + "' style='color: #ff0000' >" + stringToAdd + "</div> ");
setTimeout(function () {
if ($('#' + newid + '').length > 0) {
$('#' + newid + '').remove();
}
}, 5000);
}