r/CritiqueMyCode • u/StupidGeek00 • Sep 27 '14
/r/CritiqueMyCode is a trending SubReddit
I'm new here and this is actually how I found you guys, but I'm looking forward to posting in here.
Screenshot: http://imgur.com/elD9mTi
r/CritiqueMyCode • u/StupidGeek00 • Sep 27 '14
I'm new here and this is actually how I found you guys, but I'm looking forward to posting in here.
Screenshot: http://imgur.com/elD9mTi
r/CritiqueMyCode • u/dontworryimnotacop • Sep 27 '14
This is a small library I wrote to simplify setting up a chat between two people using WebRTC connections.
WebRTC is a relatively new standard (still doesn't work in Safari/IE atm), but it basically allows P2P connections directly between browsers (with no servers at all). You can self host this script, and use it in your browser with a friend on the other side of the world, and your communication will go directly between the two of you, double-encrypted with RTC's mandatory TLS and OpenPGP.
You can test it/see it in action here: http://github.midnightriding.com/WebRTCChat/ (open this link in two separate tabs or computers to chat between them) Prettier code (+HTML interface) is here: https://github.com/pirate/WebRTCChat
I would love any feedback on JS style, best practices, feature enhancements, anything. :) (also for this project I'm deliberately avoiding using prototypes for simplicity).
function WebRTCChat(cfg, con, myKeyPair, usePGP, theyUsePGP, sendTyping) {
var self = this;
/* WebRTC setup for broser-to-browser connection */
self.cfg = {'iceServers':[]}; //{"url":"stun:23.21.150.121"}
self.con = {'optional': [{'DtlsSrtpKeyAgreement': true}] };
self.activeChannel;
self.activeConnection;
self.roomName;
/* OpenPGP setup for chat encryption */
self.myKeyPair = null;
self.theirPubKey = "";
self.readystate = false;
self.usePGP = true;
self.theyUsePGP = true;
self.pgpStrength = 512;
self.sendTyping = true;
self.PGPdecrypt = function(message) {
pgpMessage = openpgp.message.readArmored(message);
return openpgp.decryptMessage(self.myKeyPair.key, pgpMessage);
}
self.PGPencrypt = function(message) {
return openpgp.encryptMessage(self.theirPubKey.keys, message);
}
/* WebRTC + PGP CHAT CONNECTION CODE */
/* THE HOST (initiates the chat) */
self.hostChat = function(offer_callback, ready_callback) {
var hostConnection = new RTCPeerConnection(self.cfg, self.con); // init connection
self.initConnection(hostConnection, offer_callback);
var hostChannel = hostConnection.createDataChannel('test', {reliable:true, ordered:true}); // init channel
self.initChannel(hostChannel, ready_callback);
console.log("Creating RTC Chat Host Offer...");
hostConnection.createOffer(self.handleDescription, self.handleDescriptionFailure);
// copy paste this offer to all clients who want to join
// they paste their answer back, which goes into handleAnswerFromClient
}
self.handleAnswerFromClient = function(answer) {
if (answer.pgpKey) {
self.theirPubKey = openpgp.key.readArmored(answer.pgpKey);
console.log("Received Chat Partner's Public PGP Key: ", answer.pgpKey);
}
self.theyUsePGP = Boolean(answer.encryption);
var answerDesc = new RTCSessionDescription(answer.rtc);
console.log("Received Chat RTC Join Answer: ", answerDesc);
self.activeConnection.setRemoteDescription(answerDesc);
writeToChatLog("Started hosting a chat.", "text-success alert-success");
// hostChannel.onopen will trigger once the connection is complete (enabling the chat window)
}
/* THE JOINEE (joins an existing chat) */
self.joinChat = function(offer, answer_callback, ready_callback) {
var clientConnection = new RTCPeerConnection(cfg, con);
self.initConnection(clientConnection, answer_callback);
clientConnection.ondatachannel = function (e) { // once client receives a good data channel from the host
// Chrome sends event, FF sends raw channel
var clientChannel = e.channel || e;
self.initChannel(clientChannel, ready_callback);
writeToChatLog("Joined a chat.", "text-success alert-success");
// clientChannel.onopen will then trigger once the connection is complete (enabling the chat window)
};
if (offer.pgpKey) {
self.theirPubKey = openpgp.key.readArmored(offer.pgpKey);
console.log("Received Chat Partner's Public PGP Key: ", offer.pgpKey);
}
self.theyUsePGP = Boolean(offer.encryption);
self.roomName = offer.roomName;
var offerDesc = new RTCSessionDescription(offer.rtc);
console.log("Received Chat RTC Host Offer: ", offerDesc);
self.activeConnection.setRemoteDescription(offerDesc);
console.log("Answering Chat Host Offer...");
self.activeConnection.createAnswer(self.handleDescription, self.handleDescriptionFailure);
// ondatachannel triggers once the client has accepted our answer ^
}
self.initConnection = function(conn, callback) {
self.activeConnection = conn;
self.myKeyPair = openpgp.generateKeyPair({numBits:self.pgpStrength,userId:"1",passphrase:"",unlocked:true});
// these aren't really necessary
conn.onconnection = function (state) {console.info('Chat connection complete: ', event);}
conn.onsignalingstatechange = function (state) {console.info('Signaling state change: ', state); if (self.activeConnection.iceConnectionState == "disconnected") self.writeToChatLog("Chat partner disconnected.", "text-warning alert-error");}
conn.oniceconnectionstatechange = function (state) {console.info('Signaling ICE connection state change: ', state); if (self.activeConnection.iceConnectionState == "disconnected") self.writeToChatLog("Chat partner disconnected.", "text-warning alert-error");}
conn.onicegatheringstatechange = function (state) {console.info('Signaling ICE setup state change: ', state);}
//this is the important one
conn.onicecandidate = function (event) {
// when browser has determined how to form a connection, generate offer or answer with ICE connection details and PGP public key
if (event.candidate == null) {
console.log("Valid ICE connection candidate determined.");
var offer_or_answer = JSON.stringify({
rtc: self.activeConnection.localDescription,
pgpKey: self.myKeyPair.publicKeyArmored,
encryption: self.usePGP,
roomName: self.roomName
});
// pass the offer or answer to the callback for display to the user or to send over some other communication channel
if (callback) callback(offer_or_answer);
}
};
conn.onfailure = function(details) {callback(details)};
console.log("Initialized Connection: ", conn);
}
self.initChannel = function(chan, callback) {
self.activeChannel = chan;
// once the channel is open, trigger the callback to enable the chat window or carry out other logic
chan.onopen = function (e) { console.log('Data Channel Connected.'); self.readystate = true; if (callback) callback(e);}
chan.onmessage = self.receiveMessage;
console.log("Initialized Data Channel: ", chan);
}
self.handleDescription = function(desc) {
self.activeConnection.setLocalDescription(desc, function () {});
}
self.handleDescriptionFailure = function() {
console.warn("Failed to create or answer chat offer.");
self.activeConnection.onfailure("Invalid or expired chat offer. Please try again.")
}
// messaging functions
self.sendTypingMessage = function() {
self.activeChannel.send(JSON.stringify({message:null,typing:true,encrypted:false}));
}
self.sendMessage = function(message, encrypted) {
if (Boolean(encrypted)) {
self.activeChannel.send(JSON.stringify({message: self.PGPencrypt(message), encrypted:true}));
self.writeToChatLog(message, "text-success sent secure", true);
}
else {
self.activeChannel.send(JSON.stringify({message: message, encrypted:false}));
self.writeToChatLog(message, "text-success sent insecure", false);
}
}
self.receiveMessage = function(event) {
var data = JSON.parse(event.data);
if (data.type === 'file' || event.data.size) console.log("Receiving a file.");
else {
if (data.typing && !data.message) {
console.log("Partner is typing...");
self.displayPartnerTyping();
}
else {
console.log("Received a message: ", data.message);
if (data.encrypted) self.writeToChatLog(self.PGPdecrypt(data.message), "text-info recv", true);
else self.writeToChatLog(data.message, "text-info recv", false);
}
}
}
/* Utilities */
// set these to your own functions using WebRTCChat.writeToChatLog = function(...) {...}
self.writeToChatLog = function(message, message_type, secure) {console.log("-> ", message, message_type, secure);}
self.displayPartnerTyping = function() {console.log("-> Typing...");}
}r/CritiqueMyCode • u/tgockel • Sep 26 '14
r/CritiqueMyCode • u/jamakai • Oct 01 '14
r/CritiqueMyCode • u/maandoo • Dec 22 '14
Check out my first extensions.. for blocking facebook spam comments. This works on client side hiding the comments instantly... https://chrome.google.com/webstore/detail/comment-blocker-facebook/nfpeahdgjpanjcfipcgkkdnkeicdbiaj You can checkout the code at https://github.com/srinath9795/CommentBlockerFacebook
r/CritiqueMyCode • u/Codyd51 • Sep 26 '14
r/CritiqueMyCode • u/RedMolo • Jun 06 '15
r/CritiqueMyCode • u/MeoMix • Sep 27 '14
r/CritiqueMyCode • u/n0rice • Sep 26 '14
r/CritiqueMyCode • u/M_daily • Jun 12 '15
Hey guys,
I've just started dabbling in some Python, and I made this little script that runs continuously, pulls new posts from an RSS feed (url of feed supplied via command line), and pushes an OSX notification when a new post is detected. The user can click on the notification, and it'll bring them right to the url pointed to by the new RSS object.
I tailored it to a specific website which hosts videos of cycling races, but I suppose with some modification it could be generalized.
Packages/Utilities I used:
I haven't done much OOP, nor have I done too much garbage collection so I'm looking for some advice in those areas.
e.g. does my del curFeed line make sense where it is? Could I have structured my class and its methods better?
Edits for clarity
r/CritiqueMyCode • u/[deleted] • May 08 '15
r/CritiqueMyCode • u/bong_fu_tzu • Apr 19 '15
r/CritiqueMyCode • u/chibstelford • Oct 20 '14
r/CritiqueMyCode • u/crazyMrCat • Sep 26 '14
It's far from done but I would enjoy some feedback. GitHub: https://github.com/VoidCatz/vectometry
r/CritiqueMyCode • u/Lisoph • Sep 26 '14
r/CritiqueMyCode • u/[deleted] • Aug 24 '20
The repository is https://github.com/rraallvv/csharp-client
The library was been documented in the source code. It needs a C# expert to review the code before it can be merged as part of a set of free open source tools that will be available at https://github.com/nimiq-community. Feel free to add your comments or suggestions at the PR https://github.com/nimiq-community/csharp-client/pull/1
It has GitHub Actions CI, maintainability analysis and test coverage.
r/CritiqueMyCode • u/maltiave • Apr 10 '20
r/CritiqueMyCode • u/WeAreABridge • Feb 23 '20
r/CritiqueMyCode • u/keyNONE • Aug 22 '15
I am currently trying to familiarize myself with Go. Thus, I took the wiki example from https://golang.org/doc/articles/wiki/, fleshed it out a bit and added some new features.
It would be great if you could review "gowiki.go" and let me know, what I could do better. I want to keep the code as close to the Go-Philosophy as possible.
https://github.com/senguendk/gowiki
Thank you very much and I am looking forward to your review comments.
r/CritiqueMyCode • u/Monkeypulssse • Aug 16 '15
I'm learning java and would like some feedback. Thanks
r/CritiqueMyCode • u/alexbudilovsky • Jul 14 '15
Page: http://alexbudilovsky.com/baseball_map.html GitHub: https://github.com/alexbudilovsky/baseball_map
I would appreciate all feedback!
Design choices:
collect data thru web scraping + previously compiled sql database
compose sqlite database (python script generating sqlite insert statements, then running the resulting file) with all relevant data - full 2430 game schedule and all 30 teams
python script to create a javascript page with simple dictionaries/arrays (schedule_arrays.js) holding all teams and locations, as well as all games for a each day of baseball year
no backend - HTML + javascript + Google Maps API provides all that is needed (+ one ajax call to mlb website to get xml data with live scores/previous scores)
Thanks for taking a look!
r/CritiqueMyCode • u/[deleted] • Mar 05 '15
I'm sure this is going to give someone an aneurysm but I've found it unreasonably useful as a default constructable, pretends-to-be-a-reference.... thing. I guess it acts more like a c# reference-type than anything else.
But this is all 2:00 am coffee fueled code and my eyes hurt. So if someone would be nice enough to look it over and gently tell me why it's garbage or why I'm reinventing the wheel, it would be much appreciated.
There's no comments so to clarify, "bool rvalue;" is actually, "I've been initialized with an rvalue and don't reference anything yet."
It seems to work in the limited tests I've run it through.
Be gentle please, I'm tired.
template <class T>
class element_reference
{
private:
bool rvalue;
bool ownsValue;
T* value;
public:
element_reference();
element_reference(const element_reference& other);
element_reference(T& otherValue);
element_reference(const T& otherValue);
~element_reference();
element_reference& operator=(const element_reference& rhs);
element_reference& operator=(const T& rhs);
element_reference& operator=(T& rhs);
template <class U>
operator U&() { return static_cast<U&>(*value); }
template <class U>
operator const U&() const { return static_cast<const U&>(*value); }
operator T&() { return *value; }
operator const T&() const { return *value; }
};
template <class T>
element_reference<T>::element_reference()
: element_reference(static_cast<T>(0)) { }
template <class T>
element_reference<T>::element_reference(const element_reference& other)
: value(other.value), ownsValue(false), rvalue(false) { }
template <class T>
element_reference<T>::element_reference(T& otherValue)
: value(&otherValue), ownsValue(false), rvalue(false) { }
template <class T>
element_reference<T>::element_reference(const T& otherValue)
: value(new T(otherValue)), ownsValue(true), rvalue(true) { }
template <class T>
element_reference<T>::~element_reference()
{
if (value != nullptr && ownsValue)
{
delete value;
}
value = nullptr;
}
template <class T>
element_reference<T>& element_reference<T>::operator=(const element_reference& rhs)
{
if (this != &rhs)
{
if (rhs.rvalue)
{
if (value == nullptr)
{
value = new T(*rhs.value);
ownsValue = true;
}
else
{
*value = *rhs.value;
}
}
else
{
value = rhs.value;
ownsValue = false;
}
rvalue = false;
}
return *this;
}
template <class T>
element_reference<T>& element_reference<T>::operator=(const T& rhs)
{
if (value == nullptr)
{
value = new T(rhs);
ownsValue = true;
}
else
{
*value = rhs;
}
rvalue = false;
return *this;
}
template <class T>
element_reference<T>& element_reference<T>::operator=(T& rhs)
{
if (value != nullptr && ownsValue)
{
delete value;
value = nullptr;
}
value = &rhs;
ownsValue = false;
rvalue = false;
return *this;
} edit: it breaks in a situation like this:
template <class T>
class foo
{
private:
T stuff[10];
public:
const std::vector<element_reference<T>> get_stuff() const
{
vector<element_reference<T>> resultingStuff;
for (int i = 0; i < 10; ++i)
resultingStuff.push_back(stuff[i]); //creates new pointer in constructor because const T&
return resultingStuff; //copy constructor sets addresses to doomed pointers!
}
} well, I'm stumped for now.