diff --git a/daemon/connect/Connection.cpp b/daemon/connect/Connection.cpp index 4890c549..995f93eb 100644 --- a/daemon/connect/Connection.cpp +++ b/daemon/connect/Connection.cpp @@ -62,11 +62,11 @@ static const int CONNECTION_READBUFFER_SIZE = 1024; #ifndef HAVE_GETADDRINFO #ifndef HAVE_GETHOSTBYNAME_R -Mutex* Connection::m_pMutexGetHostByName = NULL; +Mutex* Connection::m_mutexGetHostByName = NULL; #endif #endif -void closesocket_gracefully(SOCKET iSocket) +void closesocket_gracefully(SOCKET socket) { char buf[1024]; struct linger linger; @@ -75,19 +75,19 @@ void closesocket_gracefully(SOCKET iSocket) // ephemeral port exhaust problem under high QPS. linger.l_onoff = 1; linger.l_linger = 1; - setsockopt(iSocket, SOL_SOCKET, SO_LINGER, (char *) &linger, sizeof(linger)); + setsockopt(socket, SOL_SOCKET, SO_LINGER, (char *) &linger, sizeof(linger)); // Send FIN to the client - shutdown(iSocket, SHUT_WR); + shutdown(socket, SHUT_WR); // Set non-blocking mode #ifdef WIN32 unsigned long on = 1; - ioctlsocket(iSocket, FIONBIO, &on); + ioctlsocket(socket, FIONBIO, &on); #else int flags; - flags = fcntl(iSocket, F_GETFL, 0); - fcntl(iSocket, F_SETFL, flags | O_NONBLOCK); + flags = fcntl(socket, F_GETFL, 0); + fcntl(socket, F_SETFL, flags | O_NONBLOCK); #endif // Read and discard pending incoming data. If we do not do that and close the @@ -97,11 +97,11 @@ void closesocket_gracefully(SOCKET iSocket) // does recv() it gets no data back. int n; do { - n = recv(iSocket, buf, sizeof(buf), 0); + n = recv(socket, buf, sizeof(buf), 0); } while (n > 0); // Now we know that our FIN is ACK-ed, safe to close - closesocket(iSocket); + closesocket(socket); } void Connection::Init() @@ -130,7 +130,7 @@ void Connection::Init() #ifndef HAVE_GETADDRINFO #ifndef HAVE_GETHOSTBYNAME_R - m_pMutexGetHostByName = new Mutex(); + m_mutexGetHostByName = new Mutex(); #endif #endif } @@ -149,56 +149,56 @@ void Connection::Final() #ifndef HAVE_GETADDRINFO #ifndef HAVE_GETHOSTBYNAME_R - delete m_pMutexGetHostByName; + delete m_mutexGetHostByName; #endif #endif } -Connection::Connection(const char* szHost, int iPort, bool bTLS) +Connection::Connection(const char* host, int port, bool tLS) { debug("Creating Connection"); - m_szHost = NULL; - m_iPort = iPort; - m_bTLS = bTLS; - m_szCipher = NULL; - m_eStatus = csDisconnected; - m_iSocket = INVALID_SOCKET; - m_iBufAvail = 0; - m_iTimeout = 60; - m_bSuppressErrors = true; - m_szReadBuf = (char*)malloc(CONNECTION_READBUFFER_SIZE + 1); - m_iTotalBytesRead = 0; - m_bBroken = false; - m_bGracefull = false; + m_host = NULL; + m_port = port; + m_tLS = tLS; + m_cipher = NULL; + m_status = csDisconnected; + m_socket = INVALID_SOCKET; + m_bufAvail = 0; + m_timeout = 60; + m_suppressErrors = true; + m_readBuf = (char*)malloc(CONNECTION_READBUFFER_SIZE + 1); + m_totalBytesRead = 0; + m_broken = false; + m_gracefull = false; #ifndef DISABLE_TLS - m_pTLSSocket = NULL; - m_bTLSError = false; + m_tLSSocket = NULL; + m_tLSError = false; #endif - if (szHost) + if (host) { - m_szHost = strdup(szHost); + m_host = strdup(host); } } -Connection::Connection(SOCKET iSocket, bool bTLS) +Connection::Connection(SOCKET socket, bool tLS) { debug("Creating Connection"); - m_szHost = NULL; - m_iPort = 0; - m_bTLS = bTLS; - m_szCipher = NULL; - m_eStatus = csConnected; - m_iSocket = iSocket; - m_iBufAvail = 0; - m_iTimeout = 60; - m_bSuppressErrors = true; - m_szReadBuf = (char*)malloc(CONNECTION_READBUFFER_SIZE + 1); + m_host = NULL; + m_port = 0; + m_tLS = tLS; + m_cipher = NULL; + m_status = csConnected; + m_socket = socket; + m_bufAvail = 0; + m_timeout = 60; + m_suppressErrors = true; + m_readBuf = (char*)malloc(CONNECTION_READBUFFER_SIZE + 1); #ifndef DISABLE_TLS - m_pTLSSocket = NULL; - m_bTLSError = false; + m_tLSSocket = NULL; + m_tLSError = false; #endif } @@ -208,120 +208,120 @@ Connection::~Connection() Disconnect(); - free(m_szHost); - free(m_szCipher); - free(m_szReadBuf); + free(m_host); + free(m_cipher); + free(m_readBuf); #ifndef DISABLE_TLS - delete m_pTLSSocket; + delete m_tLSSocket; #endif } -void Connection::SetSuppressErrors(bool bSuppressErrors) +void Connection::SetSuppressErrors(bool suppressErrors) { - m_bSuppressErrors = bSuppressErrors; + m_suppressErrors = suppressErrors; #ifndef DISABLE_TLS - if (m_pTLSSocket) + if (m_tLSSocket) { - m_pTLSSocket->SetSuppressErrors(bSuppressErrors); + m_tLSSocket->SetSuppressErrors(suppressErrors); } #endif } -void Connection::SetCipher(const char* szCipher) +void Connection::SetCipher(const char* cipher) { - free(m_szCipher); - m_szCipher = szCipher ? strdup(szCipher) : NULL; + free(m_cipher); + m_cipher = cipher ? strdup(cipher) : NULL; } bool Connection::Connect() { debug("Connecting"); - if (m_eStatus == csConnected) + if (m_status == csConnected) { return true; } - bool bRes = DoConnect(); + bool res = DoConnect(); - if (bRes) + if (res) { - m_eStatus = csConnected; + m_status = csConnected; } else { DoDisconnect(); } - return bRes; + return res; } bool Connection::Disconnect() { debug("Disconnecting"); - if (m_eStatus == csDisconnected) + if (m_status == csDisconnected) { return true; } - bool bRes = DoDisconnect(); + bool res = DoDisconnect(); - m_eStatus = csDisconnected; - m_iSocket = INVALID_SOCKET; - m_iBufAvail = 0; + m_status = csDisconnected; + m_socket = INVALID_SOCKET; + m_bufAvail = 0; - return bRes; + return res; } bool Connection::Bind() { debug("Binding"); - if (m_eStatus == csListening) + if (m_status == csListening) { return true; } #ifdef HAVE_GETADDRINFO struct addrinfo addr_hints, *addr_list, *addr; - char iPortStr[sizeof(int) * 4 + 1]; // is enough to hold any converted int + char portStr[sizeof(int) * 4 + 1]; // is enough to hold any converted int memset(&addr_hints, 0, sizeof(addr_hints)); addr_hints.ai_family = AF_UNSPEC; // Allow IPv4 or IPv6 addr_hints.ai_socktype = SOCK_STREAM, addr_hints.ai_flags = AI_PASSIVE; // For wildcard IP address - sprintf(iPortStr, "%d", m_iPort); + sprintf(portStr, "%d", m_port); - int res = getaddrinfo(m_szHost, iPortStr, &addr_hints, &addr_list); + int res = getaddrinfo(m_host, portStr, &addr_hints, &addr_list); if (res != 0) { - ReportError("Could not resolve hostname %s", m_szHost, false, 0); + ReportError("Could not resolve hostname %s", m_host, false, 0); return false; } - m_bBroken = false; - m_iSocket = INVALID_SOCKET; + m_broken = false; + m_socket = INVALID_SOCKET; for (addr = addr_list; addr != NULL; addr = addr->ai_next) { - m_iSocket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); + m_socket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); #ifdef WIN32 - SetHandleInformation((HANDLE)m_iSocket, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation((HANDLE)m_socket, HANDLE_FLAG_INHERIT, 0); #endif - if (m_iSocket != INVALID_SOCKET) + if (m_socket != INVALID_SOCKET) { int opt = 1; - setsockopt(m_iSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt)); - res = bind(m_iSocket, addr->ai_addr, addr->ai_addrlen); + setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt)); + res = bind(m_socket, addr->ai_addr, addr->ai_addrlen); if (res != -1) { // Connection established break; } // Connection failed - closesocket(m_iSocket); - m_iSocket = INVALID_SOCKET; + closesocket(m_socket); + m_socket = INVALID_SOCKET; } } @@ -332,248 +332,248 @@ bool Connection::Bind() struct sockaddr_in sSocketAddress; memset(&sSocketAddress, 0, sizeof(sSocketAddress)); sSocketAddress.sin_family = AF_INET; - if (!m_szHost || strlen(m_szHost) == 0) + if (!m_host || strlen(m_host) == 0) { sSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY); } else { - sSocketAddress.sin_addr.s_addr = ResolveHostAddr(m_szHost); + sSocketAddress.sin_addr.s_addr = ResolveHostAddr(m_host); if (sSocketAddress.sin_addr.s_addr == (unsigned int)-1) { return false; } } - sSocketAddress.sin_port = htons(m_iPort); + sSocketAddress.sin_port = htons(m_port); - m_iSocket = socket(PF_INET, SOCK_STREAM, 0); - if (m_iSocket == INVALID_SOCKET) + m_socket = socket(PF_INET, SOCK_STREAM, 0); + if (m_socket == INVALID_SOCKET) { - ReportError("Socket creation failed for %s", m_szHost, true, 0); + ReportError("Socket creation failed for %s", m_host, true, 0); return false; } int opt = 1; - setsockopt(m_iSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt)); + setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt)); - int res = bind(m_iSocket, (struct sockaddr *) &sSocketAddress, sizeof(sSocketAddress)); + int res = bind(m_socket, (struct sockaddr *) &sSocketAddress, sizeof(sSocketAddress)); if (res == -1) { // Connection failed - closesocket(m_iSocket); - m_iSocket = INVALID_SOCKET; + closesocket(m_socket); + m_socket = INVALID_SOCKET; } #endif - if (m_iSocket == INVALID_SOCKET) + if (m_socket == INVALID_SOCKET) { - ReportError("Binding socket failed for %s", m_szHost, true, 0); + ReportError("Binding socket failed for %s", m_host, true, 0); return false; } - if (listen(m_iSocket, 100) < 0) + if (listen(m_socket, 100) < 0) { - ReportError("Listen on socket failed for %s", m_szHost, true, 0); + ReportError("Listen on socket failed for %s", m_host, true, 0); return false; } - m_eStatus = csListening; + m_status = csListening; return true; } -int Connection::WriteLine(const char* pBuffer) +int Connection::WriteLine(const char* buffer) { //debug("Connection::WriteLine"); - if (m_eStatus != csConnected) + if (m_status != csConnected) { return -1; } - int iRes = send(m_iSocket, pBuffer, strlen(pBuffer), 0); - if (iRes <= 0) + int res = send(m_socket, buffer, strlen(buffer), 0); + if (res <= 0) { - m_bBroken = true; + m_broken = true; } - return iRes; + return res; } -bool Connection::Send(const char* pBuffer, int iSize) +bool Connection::Send(const char* buffer, int size) { debug("Sending data"); - if (m_eStatus != csConnected) + if (m_status != csConnected) { return false; } - int iBytesSent = 0; - while (iBytesSent < iSize) + int bytesSent = 0; + while (bytesSent < size) { - int iRes = send(m_iSocket, pBuffer + iBytesSent, iSize-iBytesSent, 0); - if (iRes <= 0) + int res = send(m_socket, buffer + bytesSent, size-bytesSent, 0); + if (res <= 0) { - m_bBroken = true; + m_broken = true; return false; } - iBytesSent += iRes; + bytesSent += res; } return true; } -char* Connection::ReadLine(char* pBuffer, int iSize, int* pBytesRead) +char* Connection::ReadLine(char* buffer, int size, int* bytesReadOut) { - if (m_eStatus != csConnected) + if (m_status != csConnected) { return NULL; } - char* pBufPtr = pBuffer; - iSize--; // for trailing '0' - int iBytesRead = 0; - int iBufAvail = m_iBufAvail; // local variable is faster - char* szBufPtr = m_szBufPtr; // local variable is faster - while (iSize) + char* inpBuffer = buffer; + size--; // for trailing '0' + int bytesRead = 0; + int bufAvail = m_bufAvail; // local variable is faster + char* bufPtr = m_bufPtr; // local variable is faster + while (size) { - if (!iBufAvail) + if (!bufAvail) { - iBufAvail = recv(m_iSocket, m_szReadBuf, CONNECTION_READBUFFER_SIZE, 0); - if (iBufAvail < 0) + bufAvail = recv(m_socket, m_readBuf, CONNECTION_READBUFFER_SIZE, 0); + if (bufAvail < 0) { ReportError("Could not receive data on socket", NULL, true, 0); - m_bBroken = true; + m_broken = true; break; } - else if (iBufAvail == 0) + else if (bufAvail == 0) { break; } - szBufPtr = m_szReadBuf; - m_szReadBuf[iBufAvail] = '\0'; + bufPtr = m_readBuf; + m_readBuf[bufAvail] = '\0'; } int len = 0; - char* p = (char*)memchr(szBufPtr, '\n', iBufAvail); + char* p = (char*)memchr(bufPtr, '\n', bufAvail); if (p) { - len = (int)(p - szBufPtr + 1); + len = (int)(p - bufPtr + 1); } else { - len = iBufAvail; + len = bufAvail; } - if (len > iSize) + if (len > size) { - len = iSize; + len = size; } - memcpy(pBufPtr, szBufPtr, len); - pBufPtr += len; - szBufPtr += len; - iBufAvail -= len; - iBytesRead += len; - iSize -= len; + memcpy(inpBuffer, bufPtr, len); + inpBuffer += len; + bufPtr += len; + bufAvail -= len; + bytesRead += len; + size -= len; if (p) { break; } } - *pBufPtr = '\0'; + *inpBuffer = '\0'; - m_iBufAvail = iBufAvail > 0 ? iBufAvail : 0; // copy back to member - m_szBufPtr = szBufPtr; // copy back to member + m_bufAvail = bufAvail > 0 ? bufAvail : 0; // copy back to member + m_bufPtr = bufPtr; // copy back to member - if (pBytesRead) + if (bytesReadOut) { - *pBytesRead = iBytesRead; + *bytesReadOut = bytesRead; } - m_iTotalBytesRead += iBytesRead; + m_totalBytesRead += bytesRead; - if (pBufPtr == pBuffer) + if (inpBuffer == buffer) { return NULL; } - return pBuffer; + return buffer; } Connection* Connection::Accept() { debug("Accepting connection"); - if (m_eStatus != csListening) + if (m_status != csListening) { return NULL; } - SOCKET iSocket = accept(m_iSocket, NULL, NULL); - if (iSocket == INVALID_SOCKET && m_eStatus != csCancelled) + SOCKET socket = accept(m_socket, NULL, NULL); + if (socket == INVALID_SOCKET && m_status != csCancelled) { ReportError("Could not accept connection", NULL, true, 0); } - if (iSocket == INVALID_SOCKET) + if (socket == INVALID_SOCKET) { return NULL; } - Connection* pCon = new Connection(iSocket, m_bTLS); + Connection* con = new Connection(socket, m_tLS); - return pCon; + return con; } -int Connection::TryRecv(char* pBuffer, int iSize) +int Connection::TryRecv(char* buffer, int size) { debug("Receiving data"); - memset(pBuffer, 0, iSize); + memset(buffer, 0, size); - int iReceived = recv(m_iSocket, pBuffer, iSize, 0); + int received = recv(m_socket, buffer, size, 0); - if (iReceived < 0) + if (received < 0) { ReportError("Could not receive data on socket", NULL, true, 0); } - return iReceived; + return received; } -bool Connection::Recv(char * pBuffer, int iSize) +bool Connection::Recv(char * buffer, int size) { debug("Receiving data (full buffer)"); - memset(pBuffer, 0, iSize); + memset(buffer, 0, size); - char* pBufPtr = (char*)pBuffer; - int NeedBytes = iSize; + char* bufPtr = (char*)buffer; + int NeedBytes = size; - if (m_iBufAvail > 0) + if (m_bufAvail > 0) { - int len = iSize > m_iBufAvail ? m_iBufAvail : iSize; - memcpy(pBufPtr, m_szBufPtr, len); - pBufPtr += len; - m_szBufPtr += len; - m_iBufAvail -= len; + int len = size > m_bufAvail ? m_bufAvail : size; + memcpy(bufPtr, m_bufPtr, len); + bufPtr += len; + m_bufPtr += len; + m_bufAvail -= len; NeedBytes -= len; } // Read from the socket until nothing remains while (NeedBytes > 0) { - int iReceived = recv(m_iSocket, pBufPtr, NeedBytes, 0); + int received = recv(m_socket, bufPtr, NeedBytes, 0); // Did the recv succeed? - if (iReceived <= 0) + if (received <= 0) { ReportError("Could not receive data on socket", NULL, true, 0); return false; } - pBufPtr += iReceived; - NeedBytes -= iReceived; + bufPtr += received; + NeedBytes -= received; } return true; } @@ -582,28 +582,28 @@ bool Connection::DoConnect() { debug("Do connecting"); - m_iSocket = INVALID_SOCKET; - m_bBroken = false; + m_socket = INVALID_SOCKET; + m_broken = false; #ifdef HAVE_GETADDRINFO struct addrinfo addr_hints, *addr_list, *addr; - char iPortStr[sizeof(int) * 4 + 1]; //is enough to hold any converted int + char portStr[sizeof(int) * 4 + 1]; //is enough to hold any converted int memset(&addr_hints, 0, sizeof(addr_hints)); addr_hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ addr_hints.ai_socktype = SOCK_STREAM, - sprintf(iPortStr, "%d", m_iPort); + sprintf(portStr, "%d", m_port); - int res = getaddrinfo(m_szHost, iPortStr, &addr_hints, &addr_list); + int res = getaddrinfo(m_host, portStr, &addr_hints, &addr_list); if (res != 0) { - ReportError("Could not resolve hostname %s", m_szHost, true, 0); + ReportError("Could not resolve hostname %s", m_host, true, 0); return false; } std::vector triedAddr; - bool bConnected = false; + bool connected = false; for (addr = addr_list; addr != NULL; addr = addr->ai_next) { @@ -615,11 +615,11 @@ bool Connection::DoConnect() } triedAddr.push_back(sa); - m_iSocket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); + m_socket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); #ifdef WIN32 - SetHandleInformation((HANDLE)m_iSocket, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation((HANDLE)m_socket, HANDLE_FLAG_INHERIT, 0); #endif - if (m_iSocket == INVALID_SOCKET) + if (m_socket == INVALID_SOCKET) { // try another addr/family/protocol continue; @@ -628,26 +628,26 @@ bool Connection::DoConnect() if (ConnectWithTimeout(addr->ai_addr, addr->ai_addrlen)) { // Connection established - bConnected = true; + connected = true; break; } } - if (m_iSocket == INVALID_SOCKET && addr_list) + if (m_socket == INVALID_SOCKET && addr_list) { - ReportError("Socket creation failed for %s", m_szHost, true, 0); + ReportError("Socket creation failed for %s", m_host, true, 0); } - if (!bConnected && m_iSocket != INVALID_SOCKET) + if (!connected && m_socket != INVALID_SOCKET) { - ReportError("Connection to %s failed", m_szHost, true, 0); - closesocket(m_iSocket); - m_iSocket = INVALID_SOCKET; + ReportError("Connection to %s failed", m_host, true, 0); + closesocket(m_socket); + m_socket = INVALID_SOCKET; } freeaddrinfo(addr_list); - if (m_iSocket == INVALID_SOCKET) + if (m_socket == INVALID_SOCKET) { return false; } @@ -657,25 +657,25 @@ bool Connection::DoConnect() struct sockaddr_in sSocketAddress; memset(&sSocketAddress, 0, sizeof(sSocketAddress)); sSocketAddress.sin_family = AF_INET; - sSocketAddress.sin_port = htons(m_iPort); - sSocketAddress.sin_addr.s_addr = ResolveHostAddr(m_szHost); + sSocketAddress.sin_port = htons(m_port); + sSocketAddress.sin_addr.s_addr = ResolveHostAddr(m_host); if (sSocketAddress.sin_addr.s_addr == (unsigned int)-1) { return false; } - m_iSocket = socket(PF_INET, SOCK_STREAM, 0); - if (m_iSocket == INVALID_SOCKET) + m_socket = socket(PF_INET, SOCK_STREAM, 0); + if (m_socket == INVALID_SOCKET) { - ReportError("Socket creation failed for %s", m_szHost, true, 0); + ReportError("Socket creation failed for %s", m_host, true, 0); return false; } if (!ConnectWithTimeout(&sSocketAddress, sizeof(sSocketAddress))) { - ReportError("Connection to %s failed", m_szHost, true, 0); - closesocket(m_iSocket); - m_iSocket = INVALID_SOCKET; + ReportError("Connection to %s failed", m_host, true, 0); + closesocket(m_socket); + m_socket = INVALID_SOCKET; return false; } #endif @@ -686,7 +686,7 @@ bool Connection::DoConnect() } #ifndef DISABLE_TLS - if (m_bTLS && !StartTLS(true, NULL, NULL)) + if (m_tLS && !StartTLS(true, NULL, NULL)) { return false; } @@ -700,26 +700,26 @@ bool Connection::InitSocketOpts() char* optbuf = NULL; int optsize = 0; #ifdef WIN32 - int MSecVal = m_iTimeout * 1000; + int MSecVal = m_timeout * 1000; optbuf = (char*)&MSecVal; optsize = sizeof(MSecVal); #else struct timeval TimeVal; - TimeVal.tv_sec = m_iTimeout; + TimeVal.tv_sec = m_timeout; TimeVal.tv_usec = 0; optbuf = (char*)&TimeVal; optsize = sizeof(TimeVal); #endif - int err = setsockopt(m_iSocket, SOL_SOCKET, SO_RCVTIMEO, optbuf, optsize); + int err = setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, optbuf, optsize); if (err != 0) { - ReportError("Socket initialization failed for %s", m_szHost, true, 0); + ReportError("Socket initialization failed for %s", m_host, true, 0); return false; } - err = setsockopt(m_iSocket, SOL_SOCKET, SO_SNDTIMEO, optbuf, optsize); + err = setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, optbuf, optsize); if (err != 0) { - ReportError("Socket initialization failed for %s", m_szHost, true, 0); + ReportError("Socket initialization failed for %s", m_host, true, 0); return false; } return true; @@ -732,37 +732,37 @@ bool Connection::ConnectWithTimeout(void* address, int address_len) socklen_t len = sizeof(error); struct timeval ts; - ts.tv_sec = m_iTimeout; + ts.tv_sec = m_timeout; ts.tv_usec = 0; //clear out descriptor sets for select //add socket to the descriptor sets FD_ZERO(&rset); - FD_SET(m_iSocket, &rset); + FD_SET(m_socket, &rset); wset = rset; //structure assignment ok //set socket nonblocking flag #ifdef WIN32 u_long mode = 1; - if (ioctlsocket(m_iSocket, FIONBIO, &mode) != 0) + if (ioctlsocket(m_socket, FIONBIO, &mode) != 0) { return false; } #else - flags = fcntl(m_iSocket, F_GETFL, 0); + flags = fcntl(m_socket, F_GETFL, 0); if (flags < 0) { return false; } - if (fcntl(m_iSocket, F_SETFL, flags | O_NONBLOCK) < 0) + if (fcntl(m_socket, F_SETFL, flags | O_NONBLOCK) < 0) { return false; } #endif //initiate non-blocking connect - ret = connect(m_iSocket, (struct sockaddr*)address, address_len); + ret = connect(m_socket, (struct sockaddr*)address, address_len); if (ret < 0) { #ifdef WIN32 @@ -782,7 +782,7 @@ bool Connection::ConnectWithTimeout(void* address, int address_len) //connect succeeded right away? if (ret != 0) { - ret = select(m_iSocket + 1, &rset, &wset, NULL, m_iTimeout ? &ts : NULL); + ret = select(m_socket + 1, &rset, &wset, NULL, m_timeout ? &ts : NULL); //we are waiting for connect to complete now if (ret < 0) { @@ -799,13 +799,13 @@ bool Connection::ConnectWithTimeout(void* address, int address_len) return false; } - if (!(FD_ISSET(m_iSocket, &rset) || FD_ISSET(m_iSocket, &wset))) + if (!(FD_ISSET(m_socket, &rset) || FD_ISSET(m_socket, &wset))) { return false; } //we had a positivite return so a descriptor is ready - if (getsockopt(m_iSocket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) < 0) + if (getsockopt(m_socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) < 0) { return false; } @@ -821,12 +821,12 @@ bool Connection::ConnectWithTimeout(void* address, int address_len) //put socket back in blocking mode #ifdef WIN32 mode = 0; - if (ioctlsocket(m_iSocket, FIONBIO, &mode) != 0) + if (ioctlsocket(m_socket, FIONBIO, &mode) != 0) { return false; } #else - if (fcntl(m_iSocket, F_SETFL, flags) < 0) + if (fcntl(m_socket, F_SETFL, flags) < 0) { return false; } @@ -839,40 +839,40 @@ bool Connection::DoDisconnect() { debug("Do disconnecting"); - if (m_iSocket != INVALID_SOCKET) + if (m_socket != INVALID_SOCKET) { #ifndef DISABLE_TLS CloseTLS(); #endif - if (m_bGracefull) + if (m_gracefull) { - closesocket_gracefully(m_iSocket); + closesocket_gracefully(m_socket); } else { - closesocket(m_iSocket); + closesocket(m_socket); } - m_iSocket = INVALID_SOCKET; + m_socket = INVALID_SOCKET; } - m_eStatus = csDisconnected; + m_status = csDisconnected; return true; } -void Connection::ReadBuffer(char** pBuffer, int *iBufLen) +void Connection::ReadBuffer(char** buffer, int *bufLen) { - *iBufLen = m_iBufAvail; - *pBuffer = m_szBufPtr; - m_iBufAvail = 0; + *bufLen = m_bufAvail; + *buffer = m_bufPtr; + m_bufAvail = 0; }; void Connection::Cancel() { debug("Cancelling connection"); - if (m_iSocket != INVALID_SOCKET) + if (m_socket != INVALID_SOCKET) { - m_eStatus = csCancelled; - int r = shutdown(m_iSocket, SHUT_RDWR); + m_status = csCancelled; + int r = shutdown(m_socket, SHUT_RDWR); if (r == -1) { ReportError("Could not shutdown connection", NULL, true, 0); @@ -880,143 +880,143 @@ void Connection::Cancel() } } -void Connection::ReportError(const char* szMsgPrefix, const char* szMsgArg, bool PrintErrCode, int herrno) +void Connection::ReportError(const char* msgPrefix, const char* msgArg, bool PrintErrCode, int herrno) { #ifndef DISABLE_TLS - if (m_bTLSError) + if (m_tLSError) { // TLS-Error was already reported - m_bTLSError = false; + m_tLSError = false; return; } #endif - char szErrPrefix[1024]; - snprintf(szErrPrefix, 1024, szMsgPrefix, szMsgArg); - szErrPrefix[1024-1] = '\0'; + char errPrefix[1024]; + snprintf(errPrefix, 1024, msgPrefix, msgArg); + errPrefix[1024-1] = '\0'; - char szMessage[1024]; + char message[1024]; if (PrintErrCode) { #ifdef WIN32 int ErrCode = WSAGetLastError(); - char szErrMsg[1024]; - szErrMsg[0] = '\0'; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, ErrCode, 0, szErrMsg, 1024, NULL); - szErrMsg[1024-1] = '\0'; + char errMsg[1024]; + errMsg[0] = '\0'; + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, ErrCode, 0, errMsg, 1024, NULL); + errMsg[1024-1] = '\0'; #else - const char *szErrMsg = NULL; + const char *errMsg = NULL; int ErrCode = herrno; if (herrno == 0) { ErrCode = errno; - szErrMsg = strerror(ErrCode); + errMsg = strerror(ErrCode); } else { - szErrMsg = hstrerror(ErrCode); + errMsg = hstrerror(ErrCode); } #endif - if (m_bSuppressErrors) + if (m_suppressErrors) { - debug("%s: ErrNo %i, %s", szErrPrefix, ErrCode, szErrMsg); + debug("%s: ErrNo %i, %s", errPrefix, ErrCode, errMsg); } else { - snprintf(szMessage, sizeof(szMessage), "%s: ErrNo %i, %s", szErrPrefix, ErrCode, szErrMsg); - szMessage[sizeof(szMessage) - 1] = '\0'; - PrintError(szMessage); + snprintf(message, sizeof(message), "%s: ErrNo %i, %s", errPrefix, ErrCode, errMsg); + message[sizeof(message) - 1] = '\0'; + PrintError(message); } } else { - if (m_bSuppressErrors) + if (m_suppressErrors) { - debug(szErrPrefix); + debug(errPrefix); } else { - PrintError(szErrPrefix); + PrintError(errPrefix); } } } -void Connection::PrintError(const char* szErrMsg) +void Connection::PrintError(const char* errMsg) { - error("%s", szErrMsg); + error("%s", errMsg); } #ifndef DISABLE_TLS -bool Connection::StartTLS(bool bIsClient, const char* szCertFile, const char* szKeyFile) +bool Connection::StartTLS(bool isClient, const char* certFile, const char* keyFile) { debug("Starting TLS"); - delete m_pTLSSocket; - m_pTLSSocket = new ConTLSSocket(m_iSocket, bIsClient, szCertFile, szKeyFile, m_szCipher, this); - m_pTLSSocket->SetSuppressErrors(m_bSuppressErrors); + delete m_tLSSocket; + m_tLSSocket = new ConTLSSocket(m_socket, isClient, certFile, keyFile, m_cipher, this); + m_tLSSocket->SetSuppressErrors(m_suppressErrors); - return m_pTLSSocket->Start(); + return m_tLSSocket->Start(); } void Connection::CloseTLS() { - if (m_pTLSSocket) + if (m_tLSSocket) { - m_pTLSSocket->Close(); - delete m_pTLSSocket; - m_pTLSSocket = NULL; + m_tLSSocket->Close(); + delete m_tLSSocket; + m_tLSSocket = NULL; } } int Connection::recv(SOCKET s, char* buf, int len, int flags) { - int iReceived = 0; + int received = 0; - if (m_pTLSSocket) + if (m_tLSSocket) { - m_bTLSError = false; - iReceived = m_pTLSSocket->Recv(buf, len); - if (iReceived < 0) + m_tLSError = false; + received = m_tLSSocket->Recv(buf, len); + if (received < 0) { - m_bTLSError = true; + m_tLSError = true; return -1; } } else { - iReceived = ::recv(s, buf, len, flags); + received = ::recv(s, buf, len, flags); } - return iReceived; + return received; } int Connection::send(SOCKET s, const char* buf, int len, int flags) { - int iSent = 0; + int sent = 0; - if (m_pTLSSocket) + if (m_tLSSocket) { - m_bTLSError = false; - iSent = m_pTLSSocket->Send(buf, len); - if (iSent < 0) + m_tLSError = false; + sent = m_tLSSocket->Send(buf, len); + if (sent < 0) { - m_bTLSError = true; + m_tLSError = true; return -1; } - return iSent; + return sent; } else { - iSent = ::send(s, buf, len, flags); - return iSent; + sent = ::send(s, buf, len, flags); + return sent; } } #endif #ifndef HAVE_GETADDRINFO -unsigned int Connection::ResolveHostAddr(const char* szHost) +unsigned int Connection::ResolveHostAddr(const char* host) { - unsigned int uaddr = inet_addr(szHost); + unsigned int uaddr = inet_addr(host); if (uaddr == (unsigned int)-1) { struct hostent* hinfo; @@ -1026,37 +1026,37 @@ unsigned int Connection::ResolveHostAddr(const char* szHost) struct hostent hinfobuf; char strbuf[1024]; #ifdef HAVE_GETHOSTBYNAME_R_6 - err = gethostbyname_r(szHost, &hinfobuf, strbuf, sizeof(strbuf), &hinfo, &h_errnop); + err = gethostbyname_r(host, &hinfobuf, strbuf, sizeof(strbuf), &hinfo, &h_errnop); err = err || (hinfo == NULL); // error on null hinfo (means 'no entry') #endif #ifdef HAVE_GETHOSTBYNAME_R_5 - hinfo = gethostbyname_r(szHost, &hinfobuf, strbuf, sizeof(strbuf), &h_errnop); + hinfo = gethostbyname_r(host, &hinfobuf, strbuf, sizeof(strbuf), &h_errnop); err = hinfo == NULL; #endif #ifdef HAVE_GETHOSTBYNAME_R_3 //NOTE: gethostbyname_r with three parameters were not tested struct hostent_data hinfo_data; - hinfo = gethostbyname_r((char*)szHost, (struct hostent*)hinfobuf, &hinfo_data); + hinfo = gethostbyname_r((char*)host, (struct hostent*)hinfobuf, &hinfo_data); err = hinfo == NULL; #endif #else - m_pMutexGetHostByName->Lock(); - hinfo = gethostbyname(szHost); + m_mutexGetHostByName->Lock(); + hinfo = gethostbyname(host); err = hinfo == NULL; #endif if (err) { #ifndef HAVE_GETHOSTBYNAME_R - m_pMutexGetHostByName->Unlock(); + m_mutexGetHostByName->Unlock(); #endif - ReportError("Could not resolve hostname %s", szHost, true, h_errnop); + ReportError("Could not resolve hostname %s", host, true, h_errnop); return (unsigned int)-1; } memcpy(&uaddr, hinfo->h_addr_list[0], sizeof(uaddr)); #ifndef HAVE_GETHOSTBYNAME_R - m_pMutexGetHostByName->Unlock(); + m_mutexGetHostByName->Unlock(); #endif } return uaddr; @@ -1066,23 +1066,23 @@ unsigned int Connection::ResolveHostAddr(const char* szHost) const char* Connection::GetRemoteAddr() { struct sockaddr_in PeerName; - int iPeerNameLength = sizeof(PeerName); - if (getpeername(m_iSocket, (struct sockaddr*)&PeerName, (SOCKLEN_T*) &iPeerNameLength) >= 0) + int peerNameLength = sizeof(PeerName); + if (getpeername(m_socket, (struct sockaddr*)&PeerName, (SOCKLEN_T*) &peerNameLength) >= 0) { #ifdef WIN32 - strncpy(m_szRemoteAddr, inet_ntoa(PeerName.sin_addr), sizeof(m_szRemoteAddr)); + strncpy(m_remoteAddr, inet_ntoa(PeerName.sin_addr), sizeof(m_remoteAddr)); #else - inet_ntop(AF_INET, &PeerName.sin_addr, m_szRemoteAddr, sizeof(m_szRemoteAddr)); + inet_ntop(AF_INET, &PeerName.sin_addr, m_remoteAddr, sizeof(m_remoteAddr)); #endif } - m_szRemoteAddr[sizeof(m_szRemoteAddr)-1] = '\0'; + m_remoteAddr[sizeof(m_remoteAddr)-1] = '\0'; - return m_szRemoteAddr; + return m_remoteAddr; } int Connection::FetchTotalBytesRead() { - int iTotal = m_iTotalBytesRead; - m_iTotalBytesRead = 0; - return iTotal; + int total = m_totalBytesRead; + m_totalBytesRead = 0; + return total; } \ No newline at end of file diff --git a/daemon/connect/Connection.h b/daemon/connect/Connection.h index d4eb553f..928aa157 100644 --- a/daemon/connect/Connection.h +++ b/daemon/connect/Connection.h @@ -48,21 +48,21 @@ public: }; protected: - char* m_szHost; - int m_iPort; - SOCKET m_iSocket; - bool m_bTLS; - char* m_szCipher; - char* m_szReadBuf; - int m_iBufAvail; - char* m_szBufPtr; - EStatus m_eStatus; - int m_iTimeout; - bool m_bSuppressErrors; - char m_szRemoteAddr[20]; - int m_iTotalBytesRead; - bool m_bBroken; - bool m_bGracefull; + char* m_host; + int m_port; + SOCKET m_socket; + bool m_tLS; + char* m_cipher; + char* m_readBuf; + int m_bufAvail; + char* m_bufPtr; + EStatus m_status; + int m_timeout; + bool m_suppressErrors; + char m_remoteAddr[20]; + int m_totalBytesRead; + bool m_broken; + bool m_gracefull; struct SockAddr { @@ -77,33 +77,33 @@ protected: class ConTLSSocket: public TLSSocket { private: - Connection* m_pOwner; + Connection* m_owner; protected: - virtual void PrintError(const char* szErrMsg) { m_pOwner->PrintError(szErrMsg); } + virtual void PrintError(const char* errMsg) { m_owner->PrintError(errMsg); } public: - ConTLSSocket(SOCKET iSocket, bool bIsClient, const char* szCertFile, - const char* szKeyFile, const char* szCipher, Connection* pOwner): - TLSSocket(iSocket, bIsClient, szCertFile, szKeyFile, szCipher), m_pOwner(pOwner) {} + ConTLSSocket(SOCKET socket, bool isClient, const char* certFile, + const char* keyFile, const char* cipher, Connection* owner): + TLSSocket(socket, isClient, certFile, keyFile, cipher), m_owner(owner) {} }; - ConTLSSocket* m_pTLSSocket; - bool m_bTLSError; + ConTLSSocket* m_tLSSocket; + bool m_tLSError; #endif #ifndef HAVE_GETADDRINFO #ifndef HAVE_GETHOSTBYNAME_R - static Mutex* m_pMutexGetHostByName; + static Mutex* m_mutexGetHostByName; #endif #endif - Connection(SOCKET iSocket, bool bTLS); - void ReportError(const char* szMsgPrefix, const char* szMsgArg, bool PrintErrCode, int herrno); - virtual void PrintError(const char* szErrMsg); + Connection(SOCKET socket, bool tLS); + void ReportError(const char* msgPrefix, const char* msgArg, bool PrintErrCode, int herrno); + virtual void PrintError(const char* errMsg); bool DoConnect(); bool DoDisconnect(); bool InitSocketOpts(); bool ConnectWithTimeout(void* address, int address_len); #ifndef HAVE_GETADDRINFO - unsigned int ResolveHostAddr(const char* szHost); + unsigned int ResolveHostAddr(const char* host); #endif #ifndef DISABLE_TLS int recv(SOCKET s, char* buf, int len, int flags); @@ -112,35 +112,35 @@ protected: #endif public: - Connection(const char* szHost, int iPort, bool bTLS); + Connection(const char* host, int port, bool tLS); virtual ~Connection(); static void Init(); static void Final(); virtual bool Connect(); virtual bool Disconnect(); bool Bind(); - bool Send(const char* pBuffer, int iSize); - bool Recv(char* pBuffer, int iSize); - int TryRecv(char* pBuffer, int iSize); - char* ReadLine(char* pBuffer, int iSize, int* pBytesRead); - void ReadBuffer(char** pBuffer, int *iBufLen); - int WriteLine(const char* pBuffer); + bool Send(const char* buffer, int size); + bool Recv(char* buffer, int size); + int TryRecv(char* buffer, int size); + char* ReadLine(char* buffer, int size, int* bytesRead); + void ReadBuffer(char** buffer, int *bufLen); + int WriteLine(const char* buffer); Connection* Accept(); void Cancel(); - const char* GetHost() { return m_szHost; } - int GetPort() { return m_iPort; } - bool GetTLS() { return m_bTLS; } - const char* GetCipher() { return m_szCipher; } - void SetCipher(const char* szCipher); - void SetTimeout(int iTimeout) { m_iTimeout = iTimeout; } - EStatus GetStatus() { return m_eStatus; } - void SetSuppressErrors(bool bSuppressErrors); - bool GetSuppressErrors() { return m_bSuppressErrors; } + const char* GetHost() { return m_host; } + int GetPort() { return m_port; } + bool GetTLS() { return m_tLS; } + const char* GetCipher() { return m_cipher; } + void SetCipher(const char* cipher); + void SetTimeout(int timeout) { m_timeout = timeout; } + EStatus GetStatus() { return m_status; } + void SetSuppressErrors(bool suppressErrors); + bool GetSuppressErrors() { return m_suppressErrors; } const char* GetRemoteAddr(); - bool GetGracefull() { return m_bGracefull; } - void SetGracefull(bool bGracefull) { m_bGracefull = bGracefull; } + bool GetGracefull() { return m_gracefull; } + void SetGracefull(bool gracefull) { m_gracefull = gracefull; } #ifndef DISABLE_TLS - bool StartTLS(bool bIsClient, const char* szCertFile, const char* szKeyFile); + bool StartTLS(bool isClient, const char* certFile, const char* keyFile); #endif int FetchTotalBytesRead(); }; diff --git a/daemon/connect/TLS.cpp b/daemon/connect/TLS.cpp index 6cdec27a..8b70c468 100644 --- a/daemon/connect/TLS.cpp +++ b/daemon/connect/TLS.cpp @@ -87,17 +87,17 @@ Mutexes* g_pGCryptLibMutexes; static int gcry_mutex_init(void **priv) { - Mutex* pMutex = new Mutex(); - g_pGCryptLibMutexes->push_back(pMutex); - *priv = pMutex; + Mutex* mutex = new Mutex(); + g_pGCryptLibMutexes->push_back(mutex); + *priv = mutex; return 0; } static int gcry_mutex_destroy(void **lock) { - Mutex* pMutex = ((Mutex*)*lock); - g_pGCryptLibMutexes->remove(pMutex); - delete pMutex; + Mutex* mutex = ((Mutex*)*lock); + g_pGCryptLibMutexes->remove(mutex); + delete mutex; return 0; } @@ -213,9 +213,9 @@ void TLSSocket::Init() #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL - int iMaxMutexes = CRYPTO_num_locks(); - g_pOpenSSLMutexes = (Mutex**)malloc(sizeof(Mutex*)*iMaxMutexes); - for (int i=0; i < iMaxMutexes; i++) + int maxMutexes = CRYPTO_num_locks(); + g_pOpenSSLMutexes = (Mutex**)malloc(sizeof(Mutex*)*maxMutexes); + for (int i=0; i < maxMutexes; i++) { g_pOpenSSLMutexes[i] = new Mutex(); } @@ -251,8 +251,8 @@ void TLSSocket::Final() #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL - int iMaxMutexes = CRYPTO_num_locks(); - for (int i=0; i < iMaxMutexes; i++) + int maxMutexes = CRYPTO_num_locks(); + for (int i=0; i < maxMutexes; i++) { delete g_pOpenSSLMutexes[i]; } @@ -260,43 +260,43 @@ void TLSSocket::Final() #endif /* HAVE_OPENSSL */ } -TLSSocket::TLSSocket(SOCKET iSocket, bool bIsClient, const char* szCertFile, const char* szKeyFile, const char* szCipher) +TLSSocket::TLSSocket(SOCKET socket, bool isClient, const char* certFile, const char* keyFile, const char* cipher) { - m_iSocket = iSocket; - m_bIsClient = bIsClient; - m_szCertFile = szCertFile ? strdup(szCertFile) : NULL; - m_szKeyFile = szKeyFile ? strdup(szKeyFile) : NULL; - m_szCipher = szCipher && strlen(szCipher) > 0 ? strdup(szCipher) : NULL; - m_pContext = NULL; - m_pSession = NULL; - m_bSuppressErrors = false; - m_bInitialized = false; - m_bConnected = false; + m_socket = socket; + m_isClient = isClient; + m_certFile = certFile ? strdup(certFile) : NULL; + m_keyFile = keyFile ? strdup(keyFile) : NULL; + m_cipher = cipher && strlen(cipher) > 0 ? strdup(cipher) : NULL; + m_context = NULL; + m_session = NULL; + m_suppressErrors = false; + m_initialized = false; + m_connected = false; } TLSSocket::~TLSSocket() { - free(m_szCertFile); - free(m_szKeyFile); - free(m_szCipher); + free(m_certFile); + free(m_keyFile); + free(m_cipher); Close(); } -void TLSSocket::ReportError(const char* szErrMsg) +void TLSSocket::ReportError(const char* errMsg) { - char szMessage[1024]; + char message[1024]; #ifdef HAVE_LIBGNUTLS - const char* errstr = gnutls_strerror(m_iRetCode); - if (m_bSuppressErrors) + const char* errstr = gnutls_strerror(m_retCode); + if (m_suppressErrors) { - debug("%s: %s", szErrMsg, errstr); + debug("%s: %s", errMsg, errstr); } else { - snprintf(szMessage, sizeof(szMessage), "%s: %s", szErrMsg, errstr); - szMessage[sizeof(szMessage) - 1] = '\0'; - PrintError(szMessage); + snprintf(message, sizeof(message), "%s: %s", errMsg, errstr); + message[sizeof(message) - 1] = '\0'; + PrintError(message); } #endif /* HAVE_LIBGNUTLS */ @@ -310,47 +310,47 @@ void TLSSocket::ReportError(const char* szErrMsg) ERR_error_string_n(errcode, errstr, sizeof(errstr)); errstr[1024-1] = '\0'; - if (m_bSuppressErrors) + if (m_suppressErrors) { - debug("%s: %s", szErrMsg, errstr); + debug("%s: %s", errMsg, errstr); } else if (errcode != 0) { - snprintf(szMessage, sizeof(szMessage), "%s: %s", szErrMsg, errstr); - szMessage[sizeof(szMessage) - 1] = '\0'; - PrintError(szMessage); + snprintf(message, sizeof(message), "%s: %s", errMsg, errstr); + message[sizeof(message) - 1] = '\0'; + PrintError(message); } else { - PrintError(szErrMsg); + PrintError(errMsg); } } while (errcode); #endif /* HAVE_OPENSSL */ } -void TLSSocket::PrintError(const char* szErrMsg) +void TLSSocket::PrintError(const char* errMsg) { - error("%s", szErrMsg); + error("%s", errMsg); } bool TLSSocket::Start() { #ifdef HAVE_LIBGNUTLS gnutls_certificate_credentials_t cred; - m_iRetCode = gnutls_certificate_allocate_credentials(&cred); - if (m_iRetCode != 0) + m_retCode = gnutls_certificate_allocate_credentials(&cred); + if (m_retCode != 0) { ReportError("Could not create TLS context"); return false; } - m_pContext = cred; + m_context = cred; - if (m_szCertFile && m_szKeyFile) + if (m_certFile && m_keyFile) { - m_iRetCode = gnutls_certificate_set_x509_key_file((gnutls_certificate_credentials_t)m_pContext, - m_szCertFile, m_szKeyFile, GNUTLS_X509_FMT_PEM); - if (m_iRetCode != 0) + m_retCode = gnutls_certificate_set_x509_key_file((gnutls_certificate_credentials_t)m_context, + m_certFile, m_keyFile, GNUTLS_X509_FMT_PEM); + if (m_retCode != 0) { ReportError("Could not load certificate or key file"); Close(); @@ -359,69 +359,69 @@ bool TLSSocket::Start() } gnutls_session_t sess; - m_iRetCode = gnutls_init(&sess, m_bIsClient ? GNUTLS_CLIENT : GNUTLS_SERVER); - if (m_iRetCode != 0) + m_retCode = gnutls_init(&sess, m_isClient ? GNUTLS_CLIENT : GNUTLS_SERVER); + if (m_retCode != 0) { ReportError("Could not create TLS session"); Close(); return false; } - m_pSession = sess; + m_session = sess; - m_bInitialized = true; + m_initialized = true; - const char* szPriority = m_szCipher ? m_szCipher : "NORMAL"; + const char* priority = m_cipher ? m_cipher : "NORMAL"; - m_iRetCode = gnutls_priority_set_direct((gnutls_session_t)m_pSession, szPriority, NULL); - if (m_iRetCode != 0) + m_retCode = gnutls_priority_set_direct((gnutls_session_t)m_session, priority, NULL); + if (m_retCode != 0) { ReportError("Could not select cipher for TLS session"); Close(); return false; } - m_iRetCode = gnutls_credentials_set((gnutls_session_t)m_pSession, GNUTLS_CRD_CERTIFICATE, - (gnutls_certificate_credentials_t*)m_pContext); - if (m_iRetCode != 0) + m_retCode = gnutls_credentials_set((gnutls_session_t)m_session, GNUTLS_CRD_CERTIFICATE, + (gnutls_certificate_credentials_t*)m_context); + if (m_retCode != 0) { ReportError("Could not initialize TLS session"); Close(); return false; } - gnutls_transport_set_ptr((gnutls_session_t)m_pSession, (gnutls_transport_ptr_t)(size_t)m_iSocket); + gnutls_transport_set_ptr((gnutls_session_t)m_session, (gnutls_transport_ptr_t)(size_t)m_socket); - m_iRetCode = gnutls_handshake((gnutls_session_t)m_pSession); - if (m_iRetCode != 0) + m_retCode = gnutls_handshake((gnutls_session_t)m_session); + if (m_retCode != 0) { ReportError("TLS handshake failed"); Close(); return false; } - m_bConnected = true; + m_connected = true; return true; #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL - m_pContext = SSL_CTX_new(SSLv23_method()); + m_context = SSL_CTX_new(SSLv23_method()); - if (!m_pContext) + if (!m_context) { ReportError("Could not create TLS context"); return false; } - if (m_szCertFile && m_szKeyFile) + if (m_certFile && m_keyFile) { - if (SSL_CTX_use_certificate_file((SSL_CTX*)m_pContext, m_szCertFile, SSL_FILETYPE_PEM) != 1) + if (SSL_CTX_use_certificate_file((SSL_CTX*)m_context, m_certFile, SSL_FILETYPE_PEM) != 1) { ReportError("Could not load certificate file"); Close(); return false; } - if (SSL_CTX_use_PrivateKey_file((SSL_CTX*)m_pContext, m_szKeyFile, SSL_FILETYPE_PEM) != 1) + if (SSL_CTX_use_PrivateKey_file((SSL_CTX*)m_context, m_keyFile, SSL_FILETYPE_PEM) != 1) { ReportError("Could not load key file"); Close(); @@ -429,29 +429,29 @@ bool TLSSocket::Start() } } - m_pSession = SSL_new((SSL_CTX*)m_pContext); - if (!m_pSession) + m_session = SSL_new((SSL_CTX*)m_context); + if (!m_session) { ReportError("Could not create TLS session"); Close(); return false; } - if (m_szCipher && !SSL_set_cipher_list((SSL*)m_pSession, m_szCipher)) + if (m_cipher && !SSL_set_cipher_list((SSL*)m_session, m_cipher)) { ReportError("Could not select cipher for TLS"); Close(); return false; } - if (!SSL_set_fd((SSL*)m_pSession, m_iSocket)) + if (!SSL_set_fd((SSL*)m_session, m_socket)) { ReportError("Could not set the file descriptor for TLS"); Close(); return false; } - int error_code = m_bIsClient ? SSL_connect((SSL*)m_pSession) : SSL_accept((SSL*)m_pSession); + int error_code = m_isClient ? SSL_connect((SSL*)m_session) : SSL_accept((SSL*)m_session); if (error_code < 1) { ReportError("TLS handshake failed"); @@ -459,61 +459,61 @@ bool TLSSocket::Start() return false; } - m_bConnected = true; + m_connected = true; return true; #endif /* HAVE_OPENSSL */ } void TLSSocket::Close() { - if (m_pSession) + if (m_session) { #ifdef HAVE_LIBGNUTLS - if (m_bConnected) + if (m_connected) { - gnutls_bye((gnutls_session_t)m_pSession, GNUTLS_SHUT_WR); + gnutls_bye((gnutls_session_t)m_session, GNUTLS_SHUT_WR); } - if (m_bInitialized) + if (m_initialized) { - gnutls_deinit((gnutls_session_t)m_pSession); + gnutls_deinit((gnutls_session_t)m_session); } #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL - if (m_bConnected) + if (m_connected) { - SSL_shutdown((SSL*)m_pSession); + SSL_shutdown((SSL*)m_session); } - SSL_free((SSL*)m_pSession); + SSL_free((SSL*)m_session); #endif /* HAVE_OPENSSL */ - m_pSession = NULL; + m_session = NULL; } - if (m_pContext) + if (m_context) { #ifdef HAVE_LIBGNUTLS - gnutls_certificate_free_credentials((gnutls_certificate_credentials_t)m_pContext); + gnutls_certificate_free_credentials((gnutls_certificate_credentials_t)m_context); #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL - SSL_CTX_free((SSL_CTX*)m_pContext); + SSL_CTX_free((SSL_CTX*)m_context); #endif /* HAVE_OPENSSL */ - m_pContext = NULL; + m_context = NULL; } } -int TLSSocket::Send(const char* pBuffer, int iSize) +int TLSSocket::Send(const char* buffer, int size) { int ret; #ifdef HAVE_LIBGNUTLS - ret = gnutls_record_send((gnutls_session_t)m_pSession, pBuffer, iSize); + ret = gnutls_record_send((gnutls_session_t)m_session, buffer, size); #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL - ret = SSL_write((SSL*)m_pSession, pBuffer, iSize); + ret = SSL_write((SSL*)m_session, buffer, size); #endif /* HAVE_OPENSSL */ if (ret < 0) @@ -532,16 +532,16 @@ int TLSSocket::Send(const char* pBuffer, int iSize) return ret; } -int TLSSocket::Recv(char* pBuffer, int iSize) +int TLSSocket::Recv(char* buffer, int size) { int ret; #ifdef HAVE_LIBGNUTLS - ret = gnutls_record_recv((gnutls_session_t)m_pSession, pBuffer, iSize); + ret = gnutls_record_recv((gnutls_session_t)m_session, buffer, size); #endif /* HAVE_LIBGNUTLS */ #ifdef HAVE_OPENSSL - ret = SSL_read((SSL*)m_pSession, pBuffer, iSize); + ret = SSL_read((SSL*)m_session, buffer, size); #endif /* HAVE_OPENSSL */ if (ret < 0) diff --git a/daemon/connect/TLS.h b/daemon/connect/TLS.h index 4957676f..54dfd704 100644 --- a/daemon/connect/TLS.h +++ b/daemon/connect/TLS.h @@ -30,35 +30,35 @@ class TLSSocket { private: - bool m_bIsClient; - char* m_szCertFile; - char* m_szKeyFile; - char* m_szCipher; - SOCKET m_iSocket; - bool m_bSuppressErrors; - int m_iRetCode; - bool m_bInitialized; - bool m_bConnected; + bool m_isClient; + char* m_certFile; + char* m_keyFile; + char* m_cipher; + SOCKET m_socket; + bool m_suppressErrors; + int m_retCode; + bool m_initialized; + bool m_connected; // using "void*" to prevent the including of GnuTLS/OpenSSL header files into TLS.h - void* m_pContext; - void* m_pSession; + void* m_context; + void* m_session; - void ReportError(const char* szErrMsg); + void ReportError(const char* errMsg); protected: - virtual void PrintError(const char* szErrMsg); + virtual void PrintError(const char* errMsg); public: - TLSSocket(SOCKET iSocket, bool bIsClient, const char* szCertFile, const char* szKeyFile, const char* szCipher); + TLSSocket(SOCKET socket, bool isClient, const char* certFile, const char* keyFile, const char* cipher); virtual ~TLSSocket(); static void Init(); static void Final(); bool Start(); void Close(); - int Send(const char* pBuffer, int iSize); - int Recv(char* pBuffer, int iSize); - void SetSuppressErrors(bool bSuppressErrors) { m_bSuppressErrors = bSuppressErrors; } + int Send(const char* buffer, int size); + int Recv(char* buffer, int size); + void SetSuppressErrors(bool suppressErrors) { m_suppressErrors = suppressErrors; } }; #endif diff --git a/daemon/connect/WebDownloader.cpp b/daemon/connect/WebDownloader.cpp index 686e09aa..2844a3ae 100644 --- a/daemon/connect/WebDownloader.cpp +++ b/daemon/connect/WebDownloader.cpp @@ -53,15 +53,15 @@ WebDownloader::WebDownloader() { debug("Creating WebDownloader"); - m_szURL = NULL; - m_szOutputFilename = NULL; - m_pConnection = NULL; - m_szInfoName = NULL; - m_bConfirmedLength = false; - m_eStatus = adUndefined; - m_szOriginalFilename = NULL; - m_bForce = false; - m_bRetry = true; + m_url = NULL; + m_outputFilename = NULL; + m_connection = NULL; + m_infoName = NULL; + m_confirmedLength = false; + m_status = adUndefined; + m_originalFilename = NULL; + m_force = false; + m_retry = true; SetLastUpdateTimeNow(); } @@ -69,31 +69,31 @@ WebDownloader::~WebDownloader() { debug("Destroying WebDownloader"); - free(m_szURL); - free(m_szInfoName); - free(m_szOutputFilename); - free(m_szOriginalFilename); + free(m_url); + free(m_infoName); + free(m_outputFilename); + free(m_originalFilename); } void WebDownloader::SetOutputFilename(const char* v) { - m_szOutputFilename = strdup(v); + m_outputFilename = strdup(v); } void WebDownloader::SetInfoName(const char* v) { - m_szInfoName = strdup(v); + m_infoName = strdup(v); } -void WebDownloader::SetURL(const char * szURL) +void WebDownloader::SetURL(const char * url) { - free(m_szURL); - m_szURL = WebUtil::URLEncode(szURL); + free(m_url); + m_url = WebUtil::URLEncode(url); } -void WebDownloader::SetStatus(EStatus eStatus) +void WebDownloader::SetStatus(EStatus status) { - m_eStatus = eStatus; + m_status = status; Notify(NULL); } @@ -103,37 +103,37 @@ void WebDownloader::Run() SetStatus(adRunning); - int iRemainedDownloadRetries = g_pOptions->GetRetries() > 0 ? g_pOptions->GetRetries() : 1; - int iRemainedConnectRetries = iRemainedDownloadRetries > 10 ? iRemainedDownloadRetries : 10; - if (!m_bRetry) + int remainedDownloadRetries = g_pOptions->GetRetries() > 0 ? g_pOptions->GetRetries() : 1; + int remainedConnectRetries = remainedDownloadRetries > 10 ? remainedDownloadRetries : 10; + if (!m_retry) { - iRemainedDownloadRetries = 1; - iRemainedConnectRetries = 1; + remainedDownloadRetries = 1; + remainedConnectRetries = 1; } EStatus Status = adFailed; - while (!IsStopped() && iRemainedDownloadRetries > 0 && iRemainedConnectRetries > 0) + while (!IsStopped() && remainedDownloadRetries > 0 && remainedConnectRetries > 0) { SetLastUpdateTimeNow(); Status = DownloadWithRedirects(5); - if ((((Status == adFailed) && (iRemainedDownloadRetries > 1)) || - ((Status == adConnectError) && (iRemainedConnectRetries > 1))) - && !IsStopped() && !(!m_bForce && g_pOptions->GetPauseDownload())) + if ((((Status == adFailed) && (remainedDownloadRetries > 1)) || + ((Status == adConnectError) && (remainedConnectRetries > 1))) + && !IsStopped() && !(!m_force && g_pOptions->GetPauseDownload())) { detail("Waiting %i sec to retry", g_pOptions->GetRetryInterval()); int msec = 0; while (!IsStopped() && (msec < g_pOptions->GetRetryInterval() * 1000) && - !(!m_bForce && g_pOptions->GetPauseDownload())) + !(!m_force && g_pOptions->GetPauseDownload())) { usleep(100 * 1000); msec += 100; } } - if (IsStopped() || (!m_bForce && g_pOptions->GetPauseDownload())) + if (IsStopped() || (!m_force && g_pOptions->GetPauseDownload())) { Status = adRetry; break; @@ -146,11 +146,11 @@ void WebDownloader::Run() if (Status != adConnectError) { - iRemainedDownloadRetries--; + remainedDownloadRetries--; } else { - iRemainedConnectRetries--; + remainedConnectRetries--; } } @@ -163,17 +163,17 @@ void WebDownloader::Run() { if (IsStopped()) { - detail("Download %s cancelled", m_szInfoName); + detail("Download %s cancelled", m_infoName); } else { - error("Download %s failed", m_szInfoName); + error("Download %s failed", m_infoName); } } if (Status == adFinished) { - detail("Download %s completed", m_szInfoName); + detail("Download %s completed", m_infoName); } SetStatus(Status); @@ -185,7 +185,7 @@ WebDownloader::EStatus WebDownloader::Download() { EStatus Status = adRunning; - URL url(m_szURL); + URL url(m_url); Status = CreateConnection(&url); if (Status != adRunning) @@ -193,19 +193,19 @@ WebDownloader::EStatus WebDownloader::Download() return Status; } - m_pConnection->SetTimeout(g_pOptions->GetUrlTimeout()); - m_pConnection->SetSuppressErrors(false); + m_connection->SetTimeout(g_pOptions->GetUrlTimeout()); + m_connection->SetSuppressErrors(false); // connection - bool bConnected = m_pConnection->Connect(); - if (!bConnected || IsStopped()) + bool connected = m_connection->Connect(); + if (!connected || IsStopped()) { FreeConnection(); return adConnectError; } // Okay, we got a Connection. Now start downloading. - detail("Downloading %s", m_szInfoName); + detail("Downloading %s", m_infoName); SendHeaders(&url); @@ -226,132 +226,132 @@ WebDownloader::EStatus WebDownloader::Download() if (Status != adFinished) { // Download failed, delete broken output file - remove(m_szOutputFilename); + remove(m_outputFilename); } return Status; } -WebDownloader::EStatus WebDownloader::DownloadWithRedirects(int iMaxRedirects) +WebDownloader::EStatus WebDownloader::DownloadWithRedirects(int maxRedirects) { // do sync download, following redirects - EStatus eStatus = adRedirect; - while (eStatus == adRedirect && iMaxRedirects >= 0) + EStatus status = adRedirect; + while (status == adRedirect && maxRedirects >= 0) { - iMaxRedirects--; - eStatus = Download(); + maxRedirects--; + status = Download(); } - if (eStatus == adRedirect && iMaxRedirects < 0) + if (status == adRedirect && maxRedirects < 0) { - warn("Too many redirects for %s", m_szInfoName); - eStatus = adFailed; + warn("Too many redirects for %s", m_infoName); + status = adFailed; } - return eStatus; + return status; } -WebDownloader::EStatus WebDownloader::CreateConnection(URL *pUrl) +WebDownloader::EStatus WebDownloader::CreateConnection(URL *url) { - if (!pUrl->IsValid()) + if (!url->IsValid()) { - error("URL is not valid: %s", pUrl->GetAddress()); + error("URL is not valid: %s", url->GetAddress()); return adFatalError; } - int iPort = pUrl->GetPort(); - if (iPort == 0 && !strcasecmp(pUrl->GetProtocol(), "http")) + int port = url->GetPort(); + if (port == 0 && !strcasecmp(url->GetProtocol(), "http")) { - iPort = 80; + port = 80; } - if (iPort == 0 && !strcasecmp(pUrl->GetProtocol(), "https")) + if (port == 0 && !strcasecmp(url->GetProtocol(), "https")) { - iPort = 443; + port = 443; } - if (strcasecmp(pUrl->GetProtocol(), "http") && strcasecmp(pUrl->GetProtocol(), "https")) + if (strcasecmp(url->GetProtocol(), "http") && strcasecmp(url->GetProtocol(), "https")) { - error("Unsupported protocol in URL: %s", pUrl->GetAddress()); + error("Unsupported protocol in URL: %s", url->GetAddress()); return adFatalError; } #ifdef DISABLE_TLS - if (!strcasecmp(pUrl->GetProtocol(), "https")) + if (!strcasecmp(url->GetProtocol(), "https")) { - error("Program was compiled without TLS/SSL-support. Cannot download using https protocol. URL: %s", pUrl->GetAddress()); + error("Program was compiled without TLS/SSL-support. Cannot download using https protocol. URL: %s", url->GetAddress()); return adFatalError; } #endif - bool bTLS = !strcasecmp(pUrl->GetProtocol(), "https"); + bool tLS = !strcasecmp(url->GetProtocol(), "https"); - m_pConnection = new Connection(pUrl->GetHost(), iPort, bTLS); + m_connection = new Connection(url->GetHost(), port, tLS); return adRunning; } -void WebDownloader::SendHeaders(URL *pUrl) +void WebDownloader::SendHeaders(URL *url) { char tmp[1024]; // retrieve file - snprintf(tmp, 1024, "GET %s HTTP/1.0\r\n", pUrl->GetResource()); + snprintf(tmp, 1024, "GET %s HTTP/1.0\r\n", url->GetResource()); tmp[1024-1] = '\0'; - m_pConnection->WriteLine(tmp); + m_connection->WriteLine(tmp); snprintf(tmp, 1024, "User-Agent: nzbget/%s\r\n", Util::VersionRevision()); tmp[1024-1] = '\0'; - m_pConnection->WriteLine(tmp); + m_connection->WriteLine(tmp); - if ((!strcasecmp(pUrl->GetProtocol(), "http") && (pUrl->GetPort() == 80 || pUrl->GetPort() == 0)) || - (!strcasecmp(pUrl->GetProtocol(), "https") && (pUrl->GetPort() == 443 || pUrl->GetPort() == 0))) + if ((!strcasecmp(url->GetProtocol(), "http") && (url->GetPort() == 80 || url->GetPort() == 0)) || + (!strcasecmp(url->GetProtocol(), "https") && (url->GetPort() == 443 || url->GetPort() == 0))) { - snprintf(tmp, 1024, "Host: %s\r\n", pUrl->GetHost()); + snprintf(tmp, 1024, "Host: %s\r\n", url->GetHost()); } else { - snprintf(tmp, 1024, "Host: %s:%i\r\n", pUrl->GetHost(), pUrl->GetPort()); + snprintf(tmp, 1024, "Host: %s:%i\r\n", url->GetHost(), url->GetPort()); } tmp[1024-1] = '\0'; - m_pConnection->WriteLine(tmp); + m_connection->WriteLine(tmp); - m_pConnection->WriteLine("Accept: */*\r\n"); + m_connection->WriteLine("Accept: */*\r\n"); #ifndef DISABLE_GZIP - m_pConnection->WriteLine("Accept-Encoding: gzip\r\n"); + m_connection->WriteLine("Accept-Encoding: gzip\r\n"); #endif - m_pConnection->WriteLine("Connection: close\r\n"); - m_pConnection->WriteLine("\r\n"); + m_connection->WriteLine("Connection: close\r\n"); + m_connection->WriteLine("\r\n"); } WebDownloader::EStatus WebDownloader::DownloadHeaders() { EStatus Status = adRunning; - m_bConfirmedLength = false; + m_confirmedLength = false; const int LineBufSize = 1024*10; - char* szLineBuf = (char*)malloc(LineBufSize); - m_iContentLen = -1; - bool bFirstLine = true; - m_bGZip = false; - m_bRedirecting = false; - m_bRedirected = false; + char* lineBuf = (char*)malloc(LineBufSize); + m_contentLen = -1; + bool firstLine = true; + m_gZip = false; + m_redirecting = false; + m_redirected = false; // Headers while (!IsStopped()) { SetLastUpdateTimeNow(); - int iLen = 0; - char* line = m_pConnection->ReadLine(szLineBuf, LineBufSize, &iLen); + int len = 0; + char* line = m_connection->ReadLine(lineBuf, LineBufSize, &len); - if (bFirstLine) + if (firstLine) { - Status = CheckResponse(szLineBuf); + Status = CheckResponse(lineBuf); if (Status != adRunning) { break; } - bFirstLine = false; + firstLine = false; } // Have we encountered a timeout? @@ -359,7 +359,7 @@ WebDownloader::EStatus WebDownloader::DownloadHeaders() { if (!IsStopped()) { - warn("URL %s failed: Unexpected end of file", m_szInfoName); + warn("URL %s failed: Unexpected end of file", m_infoName); } Status = adFailed; break; @@ -376,14 +376,14 @@ WebDownloader::EStatus WebDownloader::DownloadHeaders() Util::TrimRight(line); ProcessHeader(line); - if (m_bRedirected) + if (m_redirected) { Status = adRedirect; break; } } - free(szLineBuf); + free(lineBuf); return Status; } @@ -392,17 +392,17 @@ WebDownloader::EStatus WebDownloader::DownloadBody() { EStatus Status = adRunning; - m_pOutFile = NULL; - bool bEnd = false; + m_outFile = NULL; + bool end = false; const int LineBufSize = 1024*10; - char* szLineBuf = (char*)malloc(LineBufSize); - int iWrittenLen = 0; + char* lineBuf = (char*)malloc(LineBufSize); + int writtenLen = 0; #ifndef DISABLE_GZIP - m_pGUnzipStream = NULL; - if (m_bGZip) + m_gUnzipStream = NULL; + if (m_gZip) { - m_pGUnzipStream = new GUnzipStream(1024*10); + m_gUnzipStream = new GUnzipStream(1024*10); } #endif @@ -411,66 +411,66 @@ WebDownloader::EStatus WebDownloader::DownloadBody() { SetLastUpdateTimeNow(); - char* szBuffer; - int iLen; - m_pConnection->ReadBuffer(&szBuffer, &iLen); - if (iLen == 0) + char* buffer; + int len; + m_connection->ReadBuffer(&buffer, &len); + if (len == 0) { - iLen = m_pConnection->TryRecv(szLineBuf, LineBufSize); - szBuffer = szLineBuf; + len = m_connection->TryRecv(lineBuf, LineBufSize); + buffer = lineBuf; } // Connection closed or timeout? - if (iLen <= 0) + if (len <= 0) { - if (iLen == 0 && m_iContentLen == -1 && iWrittenLen > 0) + if (len == 0 && m_contentLen == -1 && writtenLen > 0) { - bEnd = true; + end = true; break; } if (!IsStopped()) { - warn("URL %s failed: Unexpected end of file", m_szInfoName); + warn("URL %s failed: Unexpected end of file", m_infoName); } Status = adFailed; break; } // write to output file - if (!Write(szBuffer, iLen)) + if (!Write(buffer, len)) { Status = adFatalError; break; } - iWrittenLen += iLen; + writtenLen += len; //detect end of file - if (iWrittenLen == m_iContentLen || (m_iContentLen == -1 && m_bGZip && m_bConfirmedLength)) + if (writtenLen == m_contentLen || (m_contentLen == -1 && m_gZip && m_confirmedLength)) { - bEnd = true; + end = true; break; } } - free(szLineBuf); + free(lineBuf); #ifndef DISABLE_GZIP - delete m_pGUnzipStream; + delete m_gUnzipStream; #endif - if (m_pOutFile) + if (m_outFile) { - fclose(m_pOutFile); + fclose(m_outFile); } - if (!bEnd && Status == adRunning && !IsStopped()) + if (!end && Status == adRunning && !IsStopped()) { - warn("URL %s failed: file incomplete", m_szInfoName); + warn("URL %s failed: file incomplete", m_infoName); Status = adFailed; } - if (bEnd) + if (end) { Status = adFinished; } @@ -478,42 +478,42 @@ WebDownloader::EStatus WebDownloader::DownloadBody() return Status; } -WebDownloader::EStatus WebDownloader::CheckResponse(const char* szResponse) +WebDownloader::EStatus WebDownloader::CheckResponse(const char* response) { - if (!szResponse) + if (!response) { if (!IsStopped()) { - warn("URL %s: Connection closed by remote host", m_szInfoName); + warn("URL %s: Connection closed by remote host", m_infoName); } return adConnectError; } - const char* szHTTPResponse = strchr(szResponse, ' '); - if (strncmp(szResponse, "HTTP", 4) || !szHTTPResponse) + const char* hTTPResponse = strchr(response, ' '); + if (strncmp(response, "HTTP", 4) || !hTTPResponse) { - warn("URL %s failed: %s", m_szInfoName, szResponse); + warn("URL %s failed: %s", m_infoName, response); return adFailed; } - szHTTPResponse++; + hTTPResponse++; - if (!strncmp(szHTTPResponse, "400", 3) || !strncmp(szHTTPResponse, "499", 3)) + if (!strncmp(hTTPResponse, "400", 3) || !strncmp(hTTPResponse, "499", 3)) { - warn("URL %s failed: %s", m_szInfoName, szHTTPResponse); + warn("URL %s failed: %s", m_infoName, hTTPResponse); return adConnectError; } - else if (!strncmp(szHTTPResponse, "404", 3)) + else if (!strncmp(hTTPResponse, "404", 3)) { - warn("URL %s failed: %s", m_szInfoName, szHTTPResponse); + warn("URL %s failed: %s", m_infoName, hTTPResponse); return adNotFound; } - else if (!strncmp(szHTTPResponse, "301", 3) || !strncmp(szHTTPResponse, "302", 3)) + else if (!strncmp(hTTPResponse, "301", 3) || !strncmp(hTTPResponse, "302", 3)) { - m_bRedirecting = true; + m_redirecting = true; return adRunning; } - else if (!strncmp(szHTTPResponse, "200", 3)) + else if (!strncmp(hTTPResponse, "200", 3)) { // OK return adRunning; @@ -521,40 +521,40 @@ WebDownloader::EStatus WebDownloader::CheckResponse(const char* szResponse) else { // unknown error, no special handling - warn("URL %s failed: %s", m_szInfoName, szResponse); + warn("URL %s failed: %s", m_infoName, response); return adFailed; } } -void WebDownloader::ProcessHeader(const char* szLine) +void WebDownloader::ProcessHeader(const char* line) { - if (!strncasecmp(szLine, "Content-Length: ", 16)) + if (!strncasecmp(line, "Content-Length: ", 16)) { - m_iContentLen = atoi(szLine + 16); - m_bConfirmedLength = true; + m_contentLen = atoi(line + 16); + m_confirmedLength = true; } - else if (!strncasecmp(szLine, "Content-Encoding: gzip", 22)) + else if (!strncasecmp(line, "Content-Encoding: gzip", 22)) { - m_bGZip = true; + m_gZip = true; } - else if (!strncasecmp(szLine, "Content-Disposition: ", 21)) + else if (!strncasecmp(line, "Content-Disposition: ", 21)) { - ParseFilename(szLine); + ParseFilename(line); } - else if (m_bRedirecting && !strncasecmp(szLine, "Location: ", 10)) + else if (m_redirecting && !strncasecmp(line, "Location: ", 10)) { - ParseRedirect(szLine + 10); - m_bRedirected = true; + ParseRedirect(line + 10); + m_redirected = true; } } -void WebDownloader::ParseFilename(const char* szContentDisposition) +void WebDownloader::ParseFilename(const char* contentDisposition) { // Examples: // Content-Disposition: attachment; filename="fname.ext" // Content-Disposition: attachement;filename=fname.ext // Content-Disposition: attachement;filename=fname.ext; - const char *p = strstr(szContentDisposition, "filename"); + const char *p = strstr(contentDisposition, "filename"); if (!p) { return; @@ -582,98 +582,98 @@ void WebDownloader::ParseFilename(const char* szContentDisposition) WebUtil::HttpUnquote(fname); - free(m_szOriginalFilename); - m_szOriginalFilename = strdup(Util::BaseFileName(fname)); + free(m_originalFilename); + m_originalFilename = strdup(Util::BaseFileName(fname)); - debug("OriginalFilename: %s", m_szOriginalFilename); + debug("OriginalFilename: %s", m_originalFilename); } -void WebDownloader::ParseRedirect(const char* szLocation) +void WebDownloader::ParseRedirect(const char* location) { - const char* szNewURL = szLocation; - char szUrlBuf[1024]; - URL newUrl(szNewURL); + const char* newLocation = location; + char urlBuf[1024]; + URL newUrl(newLocation); if (!newUrl.IsValid()) { // redirect within host - char szResource[1024]; - URL oldUrl(m_szURL); + char resource[1024]; + URL oldUrl(m_url); - if (*szLocation == '/') + if (*location == '/') { // absolute path within host - strncpy(szResource, szLocation, 1024); - szResource[1024-1] = '\0'; + strncpy(resource, location, 1024); + resource[1024-1] = '\0'; } else { // relative path within host - strncpy(szResource, oldUrl.GetResource(), 1024); - szResource[1024-1] = '\0'; + strncpy(resource, oldUrl.GetResource(), 1024); + resource[1024-1] = '\0'; - char* p = strchr(szResource, '?'); + char* p = strchr(resource, '?'); if (p) { *p = '\0'; } - p = strrchr(szResource, '/'); + p = strrchr(resource, '/'); if (p) { p[1] = '\0'; } - strncat(szResource, szLocation, 1024 - strlen(szResource)); - szResource[1024-1] = '\0'; + strncat(resource, location, 1024 - strlen(resource)); + resource[1024-1] = '\0'; } if (oldUrl.GetPort() > 0) { - snprintf(szUrlBuf, 1024, "%s://%s:%i%s", oldUrl.GetProtocol(), oldUrl.GetHost(), oldUrl.GetPort(), szResource); + snprintf(urlBuf, 1024, "%s://%s:%i%s", oldUrl.GetProtocol(), oldUrl.GetHost(), oldUrl.GetPort(), resource); } else { - snprintf(szUrlBuf, 1024, "%s://%s%s", oldUrl.GetProtocol(), oldUrl.GetHost(), szResource); + snprintf(urlBuf, 1024, "%s://%s%s", oldUrl.GetProtocol(), oldUrl.GetHost(), resource); } - szUrlBuf[1024-1] = '\0'; - szNewURL = szUrlBuf; + urlBuf[1024-1] = '\0'; + newLocation = urlBuf; } - detail("URL %s redirected to %s", m_szURL, szNewURL); - SetURL(szNewURL); + detail("URL %s redirected to %s", m_url, newLocation); + SetURL(newLocation); } -bool WebDownloader::Write(void* pBuffer, int iLen) +bool WebDownloader::Write(void* buffer, int len) { - if (!m_pOutFile && !PrepareFile()) + if (!m_outFile && !PrepareFile()) { return false; } #ifndef DISABLE_GZIP - if (m_bGZip) + if (m_gZip) { - m_pGUnzipStream->Write(pBuffer, iLen); - const void *pOutBuf; - int iOutLen = 1; - while (iOutLen > 0) + m_gUnzipStream->Write(buffer, len); + const void *outBuf; + int outLen = 1; + while (outLen > 0) { - GUnzipStream::EStatus eGZStatus = m_pGUnzipStream->Read(&pOutBuf, &iOutLen); + GUnzipStream::EStatus gZStatus = m_gUnzipStream->Read(&outBuf, &outLen); - if (eGZStatus == GUnzipStream::zlError) + if (gZStatus == GUnzipStream::zlError) { - error("URL %s: GUnzip failed", m_szInfoName); + error("URL %s: GUnzip failed", m_infoName); return false; } - if (iOutLen > 0 && fwrite(pOutBuf, 1, iOutLen, m_pOutFile) <= 0) + if (outLen > 0 && fwrite(outBuf, 1, outLen, m_outFile) <= 0) { return false; } - if (eGZStatus == GUnzipStream::zlFinished) + if (gZStatus == GUnzipStream::zlFinished) { - m_bConfirmedLength = true; + m_confirmedLength = true; return true; } } @@ -682,23 +682,23 @@ bool WebDownloader::Write(void* pBuffer, int iLen) else #endif - return fwrite(pBuffer, 1, iLen, m_pOutFile) > 0; + return fwrite(buffer, 1, len, m_outFile) > 0; } bool WebDownloader::PrepareFile() { // prepare file for writing - const char* szFilename = m_szOutputFilename; - m_pOutFile = fopen(szFilename, FOPEN_WB); - if (!m_pOutFile) + const char* filename = m_outputFilename; + m_outFile = fopen(filename, FOPEN_WB); + if (!m_outFile) { - error("Could not %s file %s", "create", szFilename); + error("Could not %s file %s", "create", filename); return false; } if (g_pOptions->GetWriteBuffer() > 0) { - setvbuf(m_pOutFile, NULL, _IOFBF, g_pOptions->GetWriteBuffer() * 1024); + setvbuf(m_outFile, NULL, _IOFBF, g_pOptions->GetWriteBuffer() * 1024); } return true; @@ -706,57 +706,57 @@ bool WebDownloader::PrepareFile() void WebDownloader::LogDebugInfo() { - char szTime[50]; + char time[50]; #ifdef HAVE_CTIME_R_3 - ctime_r(&m_tLastUpdateTime, szTime, 50); + ctime_r(&m_lastUpdateTime, time, 50); #else - ctime_r(&m_tLastUpdateTime, szTime); + ctime_r(&m_lastUpdateTime, time); #endif - info(" Web-Download: status=%i, LastUpdateTime=%s, filename=%s", m_eStatus, szTime, Util::BaseFileName(m_szOutputFilename)); + info(" Web-Download: status=%i, LastUpdateTime=%s, filename=%s", m_status, time, Util::BaseFileName(m_outputFilename)); } void WebDownloader::Stop() { debug("Trying to stop WebDownloader"); Thread::Stop(); - m_mutexConnection.Lock(); - if (m_pConnection) + m_connectionMutex.Lock(); + if (m_connection) { - m_pConnection->SetSuppressErrors(true); - m_pConnection->Cancel(); + m_connection->SetSuppressErrors(true); + m_connection->Cancel(); } - m_mutexConnection.Unlock(); + m_connectionMutex.Unlock(); debug("WebDownloader stopped successfully"); } bool WebDownloader::Terminate() { - Connection* pConnection = m_pConnection; + Connection* connection = m_connection; bool terminated = Kill(); - if (terminated && pConnection) + if (terminated && connection) { debug("Terminating connection"); - pConnection->SetSuppressErrors(true); - pConnection->Cancel(); - pConnection->Disconnect(); - delete pConnection; + connection->SetSuppressErrors(true); + connection->Cancel(); + connection->Disconnect(); + delete connection; } return terminated; } void WebDownloader::FreeConnection() { - if (m_pConnection) + if (m_connection) { debug("Releasing connection"); - m_mutexConnection.Lock(); - if (m_pConnection->GetStatus() == Connection::csCancelled) + m_connectionMutex.Lock(); + if (m_connection->GetStatus() == Connection::csCancelled) { - m_pConnection->Disconnect(); + m_connection->Disconnect(); } - delete m_pConnection; - m_pConnection = NULL; - m_mutexConnection.Unlock(); + delete m_connection; + m_connection = NULL; + m_connectionMutex.Unlock(); } } diff --git a/daemon/connect/WebDownloader.h b/daemon/connect/WebDownloader.h index d85d6efe..f56b68e3 100644 --- a/daemon/connect/WebDownloader.h +++ b/daemon/connect/WebDownloader.h @@ -50,61 +50,61 @@ public: }; private: - char* m_szURL; - char* m_szOutputFilename; - Connection* m_pConnection; - Mutex m_mutexConnection; - EStatus m_eStatus; - time_t m_tLastUpdateTime; - char* m_szInfoName; - FILE* m_pOutFile; - int m_iContentLen; - bool m_bConfirmedLength; - char* m_szOriginalFilename; - bool m_bForce; - bool m_bRedirecting; - bool m_bRedirected; - bool m_bGZip; - bool m_bRetry; + char* m_url; + char* m_outputFilename; + Connection* m_connection; + Mutex m_connectionMutex; + EStatus m_status; + time_t m_lastUpdateTime; + char* m_infoName; + FILE* m_outFile; + int m_contentLen; + bool m_confirmedLength; + char* m_originalFilename; + bool m_force; + bool m_redirecting; + bool m_redirected; + bool m_gZip; + bool m_retry; #ifndef DISABLE_GZIP - GUnzipStream* m_pGUnzipStream; + GUnzipStream* m_gUnzipStream; #endif - void SetStatus(EStatus eStatus); - bool Write(void* pBuffer, int iLen); + void SetStatus(EStatus status); + bool Write(void* buffer, int len); bool PrepareFile(); void FreeConnection(); - EStatus CheckResponse(const char* szResponse); - EStatus CreateConnection(URL *pUrl); - void ParseFilename(const char* szContentDisposition); - void SendHeaders(URL *pUrl); + EStatus CheckResponse(const char* response); + EStatus CreateConnection(URL *url); + void ParseFilename(const char* contentDisposition); + void SendHeaders(URL *url); EStatus DownloadHeaders(); EStatus DownloadBody(); - void ParseRedirect(const char* szLocation); + void ParseRedirect(const char* location); protected: - virtual void ProcessHeader(const char* szLine); + virtual void ProcessHeader(const char* line); public: WebDownloader(); virtual ~WebDownloader(); - EStatus GetStatus() { return m_eStatus; } + EStatus GetStatus() { return m_status; } virtual void Run(); virtual void Stop(); EStatus Download(); - EStatus DownloadWithRedirects(int iMaxRedirects); + EStatus DownloadWithRedirects(int maxRedirects); bool Terminate(); void SetInfoName(const char* v); - const char* GetInfoName() { return m_szInfoName; } - void SetURL(const char* szURL); - const char* GetOutputFilename() { return m_szOutputFilename; } + const char* GetInfoName() { return m_infoName; } + void SetURL(const char* url); + const char* GetOutputFilename() { return m_outputFilename; } void SetOutputFilename(const char* v); - time_t GetLastUpdateTime() { return m_tLastUpdateTime; } - void SetLastUpdateTimeNow() { m_tLastUpdateTime = ::time(NULL); } - bool GetConfirmedLength() { return m_bConfirmedLength; } - const char* GetOriginalFilename() { return m_szOriginalFilename; } - void SetForce(bool bForce) { m_bForce = bForce; } - void SetRetry(bool bRetry) { m_bRetry = bRetry; } + time_t GetLastUpdateTime() { return m_lastUpdateTime; } + void SetLastUpdateTimeNow() { m_lastUpdateTime = ::time(NULL); } + bool GetConfirmedLength() { return m_confirmedLength; } + const char* GetOriginalFilename() { return m_originalFilename; } + void SetForce(bool force) { m_force = force; } + void SetRetry(bool retry) { m_retry = retry; } void LogDebugInfo(); }; diff --git a/daemon/extension/FeedScript.cpp b/daemon/extension/FeedScript.cpp index 87f78604..408907be 100644 --- a/daemon/extension/FeedScript.cpp +++ b/daemon/extension/FeedScript.cpp @@ -47,49 +47,49 @@ #include "Util.h" -void FeedScriptController::ExecuteScripts(const char* szFeedScript, const char* szFeedFile, int iFeedID) +void FeedScriptController::ExecuteScripts(const char* feedScript, const char* feedFile, int feedId) { - FeedScriptController* pScriptController = new FeedScriptController(); + FeedScriptController* scriptController = new FeedScriptController(); - pScriptController->m_szFeedFile = szFeedFile; - pScriptController->m_iFeedID = iFeedID; + scriptController->m_feedFile = feedFile; + scriptController->m_feedId = feedId; - pScriptController->ExecuteScriptList(szFeedScript); + scriptController->ExecuteScriptList(feedScript); - delete pScriptController; + delete scriptController; } -void FeedScriptController::ExecuteScript(ScriptConfig::Script* pScript) +void FeedScriptController::ExecuteScript(ScriptConfig::Script* script) { - if (!pScript->GetFeedScript()) + if (!script->GetFeedScript()) { return; } - PrintMessage(Message::mkInfo, "Executing feed-script %s for Feed%i", pScript->GetName(), m_iFeedID); + PrintMessage(Message::mkInfo, "Executing feed-script %s for Feed%i", script->GetName(), m_feedId); - SetScript(pScript->GetLocation()); + SetScript(script->GetLocation()); SetArgs(NULL, false); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "feed-script %s for Feed%i", pScript->GetName(), m_iFeedID); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "feed-script %s for Feed%i", script->GetName(), m_feedId); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - SetLogPrefix(pScript->GetDisplayName()); - PrepareParams(pScript->GetName()); + SetLogPrefix(script->GetDisplayName()); + PrepareParams(script->GetName()); Execute(); SetLogPrefix(NULL); } -void FeedScriptController::PrepareParams(const char* szScriptName) +void FeedScriptController::PrepareParams(const char* scriptName) { ResetEnv(); - SetEnvVar("NZBFP_FILENAME", m_szFeedFile); - SetIntEnvVar("NZBFP_FEEDID", m_iFeedID); + SetEnvVar("NZBFP_FILENAME", m_feedFile); + SetIntEnvVar("NZBFP_FEEDID", m_feedId); - PrepareEnvScript(NULL, szScriptName); + PrepareEnvScript(NULL, scriptName); } diff --git a/daemon/extension/FeedScript.h b/daemon/extension/FeedScript.h index d5c3f1f0..8df1c521 100644 --- a/daemon/extension/FeedScript.h +++ b/daemon/extension/FeedScript.h @@ -31,16 +31,16 @@ class FeedScriptController : public NZBScriptController { private: - const char* m_szFeedFile; - int m_iFeedID; + const char* m_feedFile; + int m_feedId; - void PrepareParams(const char* szScriptName); + void PrepareParams(const char* scriptName); protected: - virtual void ExecuteScript(ScriptConfig::Script* pScript); + virtual void ExecuteScript(ScriptConfig::Script* script); public: - static void ExecuteScripts(const char* szFeedScript, const char* szFeedFile, int iFeedID); + static void ExecuteScripts(const char* feedScript, const char* feedFile, int feedId); }; #endif diff --git a/daemon/extension/NzbScript.cpp b/daemon/extension/NzbScript.cpp index e2febfed..7b9c26ff 100644 --- a/daemon/extension/NzbScript.cpp +++ b/daemon/extension/NzbScript.cpp @@ -53,70 +53,70 @@ * are processed. The prefix is then stripped from the names. * If szStripPrefix is NULL, all pp-parameters are processed; without stripping. */ -void NZBScriptController::PrepareEnvParameters(NZBParameterList* pParameters, const char* szStripPrefix) +void NZBScriptController::PrepareEnvParameters(NZBParameterList* parameters, const char* stripPrefix) { - int iPrefixLen = szStripPrefix ? strlen(szStripPrefix) : 0; + int prefixLen = stripPrefix ? strlen(stripPrefix) : 0; - for (NZBParameterList::iterator it = pParameters->begin(); it != pParameters->end(); it++) + for (NZBParameterList::iterator it = parameters->begin(); it != parameters->end(); it++) { - NZBParameter* pParameter = *it; - const char* szValue = pParameter->GetValue(); + NZBParameter* parameter = *it; + const char* value = parameter->GetValue(); #ifdef WIN32 - char* szAnsiValue = strdup(szValue); - WebUtil::Utf8ToAnsi(szAnsiValue, strlen(szAnsiValue) + 1); - szValue = szAnsiValue; + char* ansiValue = strdup(value); + WebUtil::Utf8ToAnsi(ansiValue, strlen(ansiValue) + 1); + value = ansiValue; #endif - if (szStripPrefix && !strncmp(pParameter->GetName(), szStripPrefix, iPrefixLen) && (int)strlen(pParameter->GetName()) > iPrefixLen) + if (stripPrefix && !strncmp(parameter->GetName(), stripPrefix, prefixLen) && (int)strlen(parameter->GetName()) > prefixLen) { - SetEnvVarSpecial("NZBPR", pParameter->GetName() + iPrefixLen, szValue); + SetEnvVarSpecial("NZBPR", parameter->GetName() + prefixLen, value); } - else if (!szStripPrefix) + else if (!stripPrefix) { - SetEnvVarSpecial("NZBPR", pParameter->GetName(), szValue); + SetEnvVarSpecial("NZBPR", parameter->GetName(), value); } #ifdef WIN32 - free(szAnsiValue); + free(ansiValue); #endif } } -void NZBScriptController::PrepareEnvScript(NZBParameterList* pParameters, const char* szScriptName) +void NZBScriptController::PrepareEnvScript(NZBParameterList* parameters, const char* scriptName) { - if (pParameters) + if (parameters) { - PrepareEnvParameters(pParameters, NULL); + PrepareEnvParameters(parameters, NULL); } - char szParamPrefix[1024]; - snprintf(szParamPrefix, 1024, "%s:", szScriptName); - szParamPrefix[1024-1] = '\0'; + char paramPrefix[1024]; + snprintf(paramPrefix, 1024, "%s:", scriptName); + paramPrefix[1024-1] = '\0'; - if (pParameters) + if (parameters) { - PrepareEnvParameters(pParameters, szParamPrefix); + PrepareEnvParameters(parameters, paramPrefix); } - PrepareEnvOptions(szParamPrefix); + PrepareEnvOptions(paramPrefix); } -void NZBScriptController::ExecuteScriptList(const char* szScriptList) +void NZBScriptController::ExecuteScriptList(const char* scriptList) { for (ScriptConfig::Scripts::iterator it = g_pScriptConfig->GetScripts()->begin(); it != g_pScriptConfig->GetScripts()->end(); it++) { - ScriptConfig::Script* pScript = *it; + ScriptConfig::Script* script = *it; - if (szScriptList && *szScriptList) + if (scriptList && *scriptList) { // split szScriptList into tokens - Tokenizer tok(szScriptList, ",;"); - while (const char* szScriptName = tok.Next()) + Tokenizer tok(scriptList, ",;"); + while (const char* scriptName = tok.Next()) { - if (Util::SameFilename(szScriptName, pScript->GetName())) + if (Util::SameFilename(scriptName, script->GetName())) { - ExecuteScript(pScript); + ExecuteScript(script); break; } } diff --git a/daemon/extension/NzbScript.h b/daemon/extension/NzbScript.h index d2a5757c..0f370916 100644 --- a/daemon/extension/NzbScript.h +++ b/daemon/extension/NzbScript.h @@ -33,10 +33,10 @@ class NZBScriptController : public ScriptController { protected: - void PrepareEnvParameters(NZBParameterList* pParameters, const char* szStripPrefix); - void PrepareEnvScript(NZBParameterList* pParameters, const char* szScriptName); - void ExecuteScriptList(const char* szScriptList); - virtual void ExecuteScript(ScriptConfig::Script* pScript) = 0; + void PrepareEnvParameters(NZBParameterList* parameters, const char* stripPrefix); + void PrepareEnvScript(NZBParameterList* parameters, const char* scriptName); + void ExecuteScriptList(const char* scriptList); + virtual void ExecuteScript(ScriptConfig::Script* script) = 0; }; #endif diff --git a/daemon/extension/PostScript.cpp b/daemon/extension/PostScript.cpp index cd500d0d..6f2b5ff0 100644 --- a/daemon/extension/PostScript.cpp +++ b/daemon/extension/PostScript.cpp @@ -50,17 +50,17 @@ static const int POSTPROCESS_SUCCESS = 93; static const int POSTPROCESS_ERROR = 94; static const int POSTPROCESS_NONE = 95; -void PostScriptController::StartJob(PostInfo* pPostInfo) +void PostScriptController::StartJob(PostInfo* postInfo) { - PostScriptController* pScriptController = new PostScriptController(); - pScriptController->m_pPostInfo = pPostInfo; - pScriptController->SetWorkingDir(g_pOptions->GetDestDir()); - pScriptController->SetAutoDestroy(false); - pScriptController->m_iPrefixLen = 0; + PostScriptController* scriptController = new PostScriptController(); + scriptController->m_postInfo = postInfo; + scriptController->SetWorkingDir(g_pOptions->GetDestDir()); + scriptController->SetAutoDestroy(false); + scriptController->m_prefixLen = 0; - pPostInfo->SetPostThread(pScriptController); + postInfo->SetPostThread(scriptController); - pScriptController->Start(); + scriptController->Start(); } void PostScriptController::Run() @@ -69,157 +69,157 @@ void PostScriptController::Run() // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); - for (NZBParameterList::iterator it = m_pPostInfo->GetNZBInfo()->GetParameters()->begin(); it != m_pPostInfo->GetNZBInfo()->GetParameters()->end(); it++) + for (NZBParameterList::iterator it = m_postInfo->GetNZBInfo()->GetParameters()->begin(); it != m_postInfo->GetNZBInfo()->GetParameters()->end(); it++) { - NZBParameter* pParameter = *it; - const char* szVarname = pParameter->GetName(); - if (strlen(szVarname) > 0 && szVarname[0] != '*' && szVarname[strlen(szVarname)-1] == ':' && - (!strcasecmp(pParameter->GetValue(), "yes") || !strcasecmp(pParameter->GetValue(), "on") || !strcasecmp(pParameter->GetValue(), "1"))) + NZBParameter* parameter = *it; + const char* varname = parameter->GetName(); + if (strlen(varname) > 0 && varname[0] != '*' && varname[strlen(varname)-1] == ':' && + (!strcasecmp(parameter->GetValue(), "yes") || !strcasecmp(parameter->GetValue(), "on") || !strcasecmp(parameter->GetValue(), "1"))) { - char* szScriptName = strdup(szVarname); - szScriptName[strlen(szScriptName)-1] = '\0'; // remove trailing ':' - scriptCommaList.Append(szScriptName); + char* scriptName = strdup(varname); + scriptName[strlen(scriptName)-1] = '\0'; // remove trailing ':' + scriptCommaList.Append(scriptName); scriptCommaList.Append(","); - free(szScriptName); + free(scriptName); } } - m_pPostInfo->GetNZBInfo()->GetScriptStatuses()->Clear(); + m_postInfo->GetNZBInfo()->GetScriptStatuses()->Clear(); DownloadQueue::Unlock(); ExecuteScriptList(scriptCommaList.GetBuffer()); - m_pPostInfo->SetStage(PostInfo::ptFinished); - m_pPostInfo->SetWorking(false); + m_postInfo->SetStage(PostInfo::ptFinished); + m_postInfo->SetWorking(false); } -void PostScriptController::ExecuteScript(ScriptConfig::Script* pScript) +void PostScriptController::ExecuteScript(ScriptConfig::Script* script) { // if any script has requested par-check, do not execute other scripts - if (!pScript->GetPostScript() || m_pPostInfo->GetRequestParCheck()) + if (!script->GetPostScript() || m_postInfo->GetRequestParCheck()) { return; } - PrintMessage(Message::mkInfo, "Executing post-process-script %s for %s", pScript->GetName(), m_pPostInfo->GetNZBInfo()->GetName()); + PrintMessage(Message::mkInfo, "Executing post-process-script %s for %s", script->GetName(), m_postInfo->GetNZBInfo()->GetName()); - char szProgressLabel[1024]; - snprintf(szProgressLabel, 1024, "Executing post-process-script %s", pScript->GetName()); - szProgressLabel[1024-1] = '\0'; + char progressLabel[1024]; + snprintf(progressLabel, 1024, "Executing post-process-script %s", script->GetName()); + progressLabel[1024-1] = '\0'; DownloadQueue::Lock(); - m_pPostInfo->SetProgressLabel(szProgressLabel); + m_postInfo->SetProgressLabel(progressLabel); DownloadQueue::Unlock(); - SetScript(pScript->GetLocation()); + SetScript(script->GetLocation()); SetArgs(NULL, false); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "post-process-script %s for %s", pScript->GetName(), m_pPostInfo->GetNZBInfo()->GetName()); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "post-process-script %s for %s", script->GetName(), m_postInfo->GetNZBInfo()->GetName()); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - m_pScript = pScript; - SetLogPrefix(pScript->GetDisplayName()); - m_iPrefixLen = strlen(pScript->GetDisplayName()) + 2; // 2 = strlen(": "); - PrepareParams(pScript->GetName()); + m_script = script; + SetLogPrefix(script->GetDisplayName()); + m_prefixLen = strlen(script->GetDisplayName()) + 2; // 2 = strlen(": "); + PrepareParams(script->GetName()); - int iExitCode = Execute(); + int exitCode = Execute(); - szInfoName[0] = 'P'; // uppercase + infoName[0] = 'P'; // uppercase SetLogPrefix(NULL); - ScriptStatus::EStatus eStatus = AnalyseExitCode(iExitCode); + ScriptStatus::EStatus status = AnalyseExitCode(exitCode); // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); - m_pPostInfo->GetNZBInfo()->GetScriptStatuses()->Add(pScript->GetName(), eStatus); + m_postInfo->GetNZBInfo()->GetScriptStatuses()->Add(script->GetName(), status); DownloadQueue::Unlock(); } -void PostScriptController::PrepareParams(const char* szScriptName) +void PostScriptController::PrepareParams(const char* scriptName) { // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); ResetEnv(); - SetIntEnvVar("NZBPP_NZBID", m_pPostInfo->GetNZBInfo()->GetID()); - SetEnvVar("NZBPP_NZBNAME", m_pPostInfo->GetNZBInfo()->GetName()); - SetEnvVar("NZBPP_DIRECTORY", m_pPostInfo->GetNZBInfo()->GetDestDir()); - SetEnvVar("NZBPP_NZBFILENAME", m_pPostInfo->GetNZBInfo()->GetFilename()); - SetEnvVar("NZBPP_URL", m_pPostInfo->GetNZBInfo()->GetURL()); - SetEnvVar("NZBPP_FINALDIR", m_pPostInfo->GetNZBInfo()->GetFinalDir()); - SetEnvVar("NZBPP_CATEGORY", m_pPostInfo->GetNZBInfo()->GetCategory()); - SetIntEnvVar("NZBPP_HEALTH", m_pPostInfo->GetNZBInfo()->CalcHealth()); - SetIntEnvVar("NZBPP_CRITICALHEALTH", m_pPostInfo->GetNZBInfo()->CalcCriticalHealth(false)); + SetIntEnvVar("NZBPP_NZBID", m_postInfo->GetNZBInfo()->GetID()); + SetEnvVar("NZBPP_NZBNAME", m_postInfo->GetNZBInfo()->GetName()); + SetEnvVar("NZBPP_DIRECTORY", m_postInfo->GetNZBInfo()->GetDestDir()); + SetEnvVar("NZBPP_NZBFILENAME", m_postInfo->GetNZBInfo()->GetFilename()); + SetEnvVar("NZBPP_URL", m_postInfo->GetNZBInfo()->GetURL()); + SetEnvVar("NZBPP_FINALDIR", m_postInfo->GetNZBInfo()->GetFinalDir()); + SetEnvVar("NZBPP_CATEGORY", m_postInfo->GetNZBInfo()->GetCategory()); + SetIntEnvVar("NZBPP_HEALTH", m_postInfo->GetNZBInfo()->CalcHealth()); + SetIntEnvVar("NZBPP_CRITICALHEALTH", m_postInfo->GetNZBInfo()->CalcCriticalHealth(false)); - SetEnvVar("NZBPP_DUPEKEY", m_pPostInfo->GetNZBInfo()->GetDupeKey()); - SetIntEnvVar("NZBPP_DUPESCORE", m_pPostInfo->GetNZBInfo()->GetDupeScore()); + SetEnvVar("NZBPP_DUPEKEY", m_postInfo->GetNZBInfo()->GetDupeKey()); + SetIntEnvVar("NZBPP_DUPESCORE", m_postInfo->GetNZBInfo()->GetDupeScore()); - const char* szDupeModeName[] = { "SCORE", "ALL", "FORCE" }; - SetEnvVar("NZBPP_DUPEMODE", szDupeModeName[m_pPostInfo->GetNZBInfo()->GetDupeMode()]); + const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; + SetEnvVar("NZBPP_DUPEMODE", dupeModeName[m_postInfo->GetNZBInfo()->GetDupeMode()]); - char szStatus[256]; - strncpy(szStatus, m_pPostInfo->GetNZBInfo()->MakeTextStatus(true), sizeof(szStatus)); - szStatus[256-1] = '\0'; - SetEnvVar("NZBPP_STATUS", szStatus); + char status[256]; + strncpy(status, m_postInfo->GetNZBInfo()->MakeTextStatus(true), sizeof(status)); + status[256-1] = '\0'; + SetEnvVar("NZBPP_STATUS", status); - char* szDetail = strchr(szStatus, '/'); - if (szDetail) *szDetail = '\0'; - SetEnvVar("NZBPP_TOTALSTATUS", szStatus); + char* detail = strchr(status, '/'); + if (detail) *detail = '\0'; + SetEnvVar("NZBPP_TOTALSTATUS", status); - const char* szScriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; - SetEnvVar("NZBPP_SCRIPTSTATUS", szScriptStatusName[m_pPostInfo->GetNZBInfo()->GetScriptStatuses()->CalcTotalStatus()]); + const char* scriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; + SetEnvVar("NZBPP_SCRIPTSTATUS", scriptStatusName[m_postInfo->GetNZBInfo()->GetScriptStatuses()->CalcTotalStatus()]); // deprecated - int iParStatus[] = { 0, 0, 1, 2, 3, 4 }; - NZBInfo::EParStatus eParStatus = m_pPostInfo->GetNZBInfo()->GetParStatus(); + int parStatusCodes[] = { 0, 0, 1, 2, 3, 4 }; + NZBInfo::EParStatus parStatus = m_postInfo->GetNZBInfo()->GetParStatus(); // for downloads marked as bad and for deleted downloads pass par status "Failure" // for compatibility with older scripts which don't check "NZBPP_TOTALSTATUS" - if (m_pPostInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsNone || - m_pPostInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksBad) + if (m_postInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsNone || + m_postInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksBad) { - eParStatus = NZBInfo::psFailure; + parStatus = NZBInfo::psFailure; } - SetIntEnvVar("NZBPP_PARSTATUS", iParStatus[eParStatus]); + SetIntEnvVar("NZBPP_PARSTATUS", parStatusCodes[parStatus]); // deprecated - int iUnpackStatus[] = { 0, 0, 1, 2, 3, 4 }; - SetIntEnvVar("NZBPP_UNPACKSTATUS", iUnpackStatus[m_pPostInfo->GetNZBInfo()->GetUnpackStatus()]); + int unpackStatus[] = { 0, 0, 1, 2, 3, 4 }; + SetIntEnvVar("NZBPP_UNPACKSTATUS", unpackStatus[m_postInfo->GetNZBInfo()->GetUnpackStatus()]); // deprecated - SetIntEnvVar("NZBPP_HEALTHDELETED", (int)m_pPostInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsHealth); + SetIntEnvVar("NZBPP_HEALTHDELETED", (int)m_postInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsHealth); - SetIntEnvVar("NZBPP_TOTALARTICLES", (int)m_pPostInfo->GetNZBInfo()->GetTotalArticles()); - SetIntEnvVar("NZBPP_SUCCESSARTICLES", (int)m_pPostInfo->GetNZBInfo()->GetSuccessArticles()); - SetIntEnvVar("NZBPP_FAILEDARTICLES", (int)m_pPostInfo->GetNZBInfo()->GetFailedArticles()); + SetIntEnvVar("NZBPP_TOTALARTICLES", (int)m_postInfo->GetNZBInfo()->GetTotalArticles()); + SetIntEnvVar("NZBPP_SUCCESSARTICLES", (int)m_postInfo->GetNZBInfo()->GetSuccessArticles()); + SetIntEnvVar("NZBPP_FAILEDARTICLES", (int)m_postInfo->GetNZBInfo()->GetFailedArticles()); - for (ServerStatList::iterator it = m_pPostInfo->GetNZBInfo()->GetServerStats()->begin(); it != m_pPostInfo->GetNZBInfo()->GetServerStats()->end(); it++) + for (ServerStatList::iterator it = m_postInfo->GetNZBInfo()->GetServerStats()->begin(); it != m_postInfo->GetNZBInfo()->GetServerStats()->end(); it++) { - ServerStat* pServerStat = *it; + ServerStat* serverStat = *it; - char szName[50]; + char name[50]; - snprintf(szName, 50, "NZBPP_SERVER%i_SUCCESSARTICLES", pServerStat->GetServerID()); - szName[50-1] = '\0'; - SetIntEnvVar(szName, pServerStat->GetSuccessArticles()); + snprintf(name, 50, "NZBPP_SERVER%i_SUCCESSARTICLES", serverStat->GetServerID()); + name[50-1] = '\0'; + SetIntEnvVar(name, serverStat->GetSuccessArticles()); - snprintf(szName, 50, "NZBPP_SERVER%i_FAILEDARTICLES", pServerStat->GetServerID()); - szName[50-1] = '\0'; - SetIntEnvVar(szName, pServerStat->GetFailedArticles()); + snprintf(name, 50, "NZBPP_SERVER%i_FAILEDARTICLES", serverStat->GetServerID()); + name[50-1] = '\0'; + SetIntEnvVar(name, serverStat->GetFailedArticles()); } - PrepareEnvScript(m_pPostInfo->GetNZBInfo()->GetParameters(), szScriptName); + PrepareEnvScript(m_postInfo->GetNZBInfo()->GetParameters(), scriptName); DownloadQueue::Unlock(); } -ScriptStatus::EStatus PostScriptController::AnalyseExitCode(int iExitCode) +ScriptStatus::EStatus PostScriptController::AnalyseExitCode(int exitCode) { // The ScriptStatus is accumulated for all scripts: // If any script has failed the status is "failure", etc. - switch (iExitCode) + switch (exitCode) { case POSTPROCESS_SUCCESS: PrintMessage(Message::mkInfo, "%s successful", GetInfoName()); @@ -236,7 +236,7 @@ ScriptStatus::EStatus PostScriptController::AnalyseExitCode(int iExitCode) #ifndef DISABLE_PARCHECK case POSTPROCESS_PARCHECK: - if (m_pPostInfo->GetNZBInfo()->GetParStatus() > NZBInfo::psSkipped) + if (m_postInfo->GetNZBInfo()->GetParStatus() > NZBInfo::psSkipped) { PrintMessage(Message::mkError, "%s requested par-check/repair, but the collection was already checked", GetInfoName()); return ScriptStatus::srFailure; @@ -244,8 +244,8 @@ ScriptStatus::EStatus PostScriptController::AnalyseExitCode(int iExitCode) else { PrintMessage(Message::mkInfo, "%s requested par-check/repair", GetInfoName()); - m_pPostInfo->SetRequestParCheck(true); - m_pPostInfo->SetForceRepair(true); + m_postInfo->SetRequestParCheck(true); + m_postInfo->SetForceRepair(true); return ScriptStatus::srSuccess; } break; @@ -257,87 +257,87 @@ ScriptStatus::EStatus PostScriptController::AnalyseExitCode(int iExitCode) } } -void PostScriptController::AddMessage(Message::EKind eKind, const char* szText) +void PostScriptController::AddMessage(Message::EKind kind, const char* text) { - const char* szMsgText = szText + m_iPrefixLen; + const char* msgText = text + m_prefixLen; - if (!strncmp(szMsgText, "[NZB] ", 6)) + if (!strncmp(msgText, "[NZB] ", 6)) { - debug("Command %s detected", szMsgText + 6); - if (!strncmp(szMsgText + 6, "FINALDIR=", 9)) + debug("Command %s detected", msgText + 6); + if (!strncmp(msgText + 6, "FINALDIR=", 9)) { DownloadQueue::Lock(); - m_pPostInfo->GetNZBInfo()->SetFinalDir(szMsgText + 6 + 9); + m_postInfo->GetNZBInfo()->SetFinalDir(msgText + 6 + 9); DownloadQueue::Unlock(); } - else if (!strncmp(szMsgText + 6, "DIRECTORY=", 10)) + else if (!strncmp(msgText + 6, "DIRECTORY=", 10)) { DownloadQueue::Lock(); - m_pPostInfo->GetNZBInfo()->SetDestDir(szMsgText + 6 + 10); + m_postInfo->GetNZBInfo()->SetDestDir(msgText + 6 + 10); DownloadQueue::Unlock(); } - else if (!strncmp(szMsgText + 6, "NZBPR_", 6)) + else if (!strncmp(msgText + 6, "NZBPR_", 6)) { - char* szParam = strdup(szMsgText + 6 + 6); - char* szValue = strchr(szParam, '='); - if (szValue) + char* param = strdup(msgText + 6 + 6); + char* value = strchr(param, '='); + if (value) { - *szValue = '\0'; + *value = '\0'; DownloadQueue::Lock(); - m_pPostInfo->GetNZBInfo()->GetParameters()->SetParameter(szParam, szValue + 1); + m_postInfo->GetNZBInfo()->GetParameters()->SetParameter(param, value + 1); DownloadQueue::Unlock(); } else { - m_pPostInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Invalid command \"%s\" received from %s", szMsgText, GetInfoName()); + m_postInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Invalid command \"%s\" received from %s", msgText, GetInfoName()); } - free(szParam); + free(param); } - else if (!strncmp(szMsgText + 6, "MARK=BAD", 8)) + else if (!strncmp(msgText + 6, "MARK=BAD", 8)) { SetLogPrefix(NULL); - PrintMessage(Message::mkWarning, "Marking %s as bad", m_pPostInfo->GetNZBInfo()->GetName()); - SetLogPrefix(m_pScript->GetDisplayName()); - m_pPostInfo->GetNZBInfo()->SetMarkStatus(NZBInfo::ksBad); + PrintMessage(Message::mkWarning, "Marking %s as bad", m_postInfo->GetNZBInfo()->GetName()); + SetLogPrefix(m_script->GetDisplayName()); + m_postInfo->GetNZBInfo()->SetMarkStatus(NZBInfo::ksBad); } else { - m_pPostInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Invalid command \"%s\" received from %s", szMsgText, GetInfoName()); + m_postInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Invalid command \"%s\" received from %s", msgText, GetInfoName()); } } else { - m_pPostInfo->GetNZBInfo()->AddMessage(eKind, szText); + m_postInfo->GetNZBInfo()->AddMessage(kind, text); DownloadQueue::Lock(); - m_pPostInfo->SetProgressLabel(szText); + m_postInfo->SetProgressLabel(text); DownloadQueue::Unlock(); } - if (g_pOptions->GetPausePostProcess() && !m_pPostInfo->GetNZBInfo()->GetForcePriority()) + if (g_pOptions->GetPausePostProcess() && !m_postInfo->GetNZBInfo()->GetForcePriority()) { - time_t tStageTime = m_pPostInfo->GetStageTime(); - time_t tStartTime = m_pPostInfo->GetStartTime(); - time_t tWaitTime = time(NULL); + time_t stageTime = m_postInfo->GetStageTime(); + time_t startTime = m_postInfo->GetStartTime(); + time_t waitTime = time(NULL); // wait until Post-processor is unpaused - while (g_pOptions->GetPausePostProcess() && !m_pPostInfo->GetNZBInfo()->GetForcePriority() && !IsStopped()) + while (g_pOptions->GetPausePostProcess() && !m_postInfo->GetNZBInfo()->GetForcePriority() && !IsStopped()) { usleep(100 * 1000); // update time stamps - time_t tDelta = time(NULL) - tWaitTime; + time_t delta = time(NULL) - waitTime; - if (tStageTime > 0) + if (stageTime > 0) { - m_pPostInfo->SetStageTime(tStageTime + tDelta); + m_postInfo->SetStageTime(stageTime + delta); } - if (tStartTime > 0) + if (startTime > 0) { - m_pPostInfo->SetStartTime(tStartTime + tDelta); + m_postInfo->SetStartTime(startTime + delta); } } } diff --git a/daemon/extension/PostScript.h b/daemon/extension/PostScript.h index 3a1f6db0..b85c82ec 100644 --- a/daemon/extension/PostScript.h +++ b/daemon/extension/PostScript.h @@ -32,21 +32,21 @@ class PostScriptController : public Thread, public NZBScriptController { private: - PostInfo* m_pPostInfo; - int m_iPrefixLen; - ScriptConfig::Script* m_pScript; + PostInfo* m_postInfo; + int m_prefixLen; + ScriptConfig::Script* m_script; - void PrepareParams(const char* szScriptName); - ScriptStatus::EStatus AnalyseExitCode(int iExitCode); + void PrepareParams(const char* scriptName); + ScriptStatus::EStatus AnalyseExitCode(int exitCode); protected: - virtual void ExecuteScript(ScriptConfig::Script* pScript); - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void ExecuteScript(ScriptConfig::Script* script); + virtual void AddMessage(Message::EKind kind, const char* text); public: virtual void Run(); virtual void Stop(); - static void StartJob(PostInfo* pPostInfo); + static void StartJob(PostInfo* postInfo); }; #endif diff --git a/daemon/extension/QueueScript.cpp b/daemon/extension/QueueScript.cpp index 1f50cc29..4f216d14 100644 --- a/daemon/extension/QueueScript.cpp +++ b/daemon/extension/QueueScript.cpp @@ -52,88 +52,88 @@ static const char* QUEUE_EVENT_NAMES[] = { "FILE_DOWNLOADED", "URL_COMPLETED", " class QueueScriptController : public Thread, public NZBScriptController { private: - char* m_szNZBName; - char* m_szNZBFilename; - char* m_szUrl; - char* m_szCategory; - char* m_szDestDir; - int m_iID; - int m_iPriority; - char* m_szDupeKey; - EDupeMode m_eDupeMode; - int m_iDupeScore; - NZBParameterList m_Parameters; - int m_iPrefixLen; - ScriptConfig::Script* m_pScript; - QueueScriptCoordinator::EEvent m_eEvent; - bool m_bMarkBad; - NZBInfo::EDeleteStatus m_eDeleteStatus; - NZBInfo::EUrlStatus m_eUrlStatus; + char* m_nzbName; + char* m_nzbFilename; + char* m_url; + char* m_category; + char* m_destDir; + int m_id; + int m_priority; + char* m_dupeKey; + EDupeMode m_dupeMode; + int m_dupeScore; + NZBParameterList m_parameters; + int m_prefixLen; + ScriptConfig::Script* m_script; + QueueScriptCoordinator::EEvent m_event; + bool m_markBad; + NZBInfo::EDeleteStatus m_deleteStatus; + NZBInfo::EUrlStatus m_urlStatus; - void PrepareParams(const char* szScriptName); + void PrepareParams(const char* scriptName); protected: - virtual void ExecuteScript(ScriptConfig::Script* pScript); - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void ExecuteScript(ScriptConfig::Script* script); + virtual void AddMessage(Message::EKind kind, const char* text); public: virtual ~QueueScriptController(); virtual void Run(); - static void StartScript(NZBInfo* pNZBInfo, ScriptConfig::Script* pScript, QueueScriptCoordinator::EEvent eEvent); + static void StartScript(NZBInfo* nzbInfo, ScriptConfig::Script* script, QueueScriptCoordinator::EEvent event); }; QueueScriptController::~QueueScriptController() { - free(m_szNZBName); - free(m_szNZBFilename); - free(m_szUrl); - free(m_szCategory); - free(m_szDestDir); - free(m_szDupeKey); + free(m_nzbName); + free(m_nzbFilename); + free(m_url); + free(m_category); + free(m_destDir); + free(m_dupeKey); } -void QueueScriptController::StartScript(NZBInfo* pNZBInfo, ScriptConfig::Script* pScript, QueueScriptCoordinator::EEvent eEvent) +void QueueScriptController::StartScript(NZBInfo* nzbInfo, ScriptConfig::Script* script, QueueScriptCoordinator::EEvent event) { - QueueScriptController* pScriptController = new QueueScriptController(); + QueueScriptController* scriptController = new QueueScriptController(); - pScriptController->m_szNZBName = strdup(pNZBInfo->GetName()); - pScriptController->m_szNZBFilename = strdup(pNZBInfo->GetFilename()); - pScriptController->m_szUrl = strdup(pNZBInfo->GetURL()); - pScriptController->m_szCategory = strdup(pNZBInfo->GetCategory()); - pScriptController->m_szDestDir = strdup(pNZBInfo->GetDestDir()); - pScriptController->m_iID = pNZBInfo->GetID(); - pScriptController->m_iPriority = pNZBInfo->GetPriority(); - pScriptController->m_szDupeKey = strdup(pNZBInfo->GetDupeKey()); - pScriptController->m_eDupeMode = pNZBInfo->GetDupeMode(); - pScriptController->m_iDupeScore = pNZBInfo->GetDupeScore(); - pScriptController->m_Parameters.CopyFrom(pNZBInfo->GetParameters()); - pScriptController->m_pScript = pScript; - pScriptController->m_eEvent = eEvent; - pScriptController->m_iPrefixLen = 0; - pScriptController->m_bMarkBad = false; - pScriptController->m_eDeleteStatus = pNZBInfo->GetDeleteStatus(); - pScriptController->m_eUrlStatus = pNZBInfo->GetUrlStatus(); - pScriptController->SetAutoDestroy(true); + scriptController->m_nzbName = strdup(nzbInfo->GetName()); + scriptController->m_nzbFilename = strdup(nzbInfo->GetFilename()); + scriptController->m_url = strdup(nzbInfo->GetURL()); + scriptController->m_category = strdup(nzbInfo->GetCategory()); + scriptController->m_destDir = strdup(nzbInfo->GetDestDir()); + scriptController->m_id = nzbInfo->GetID(); + scriptController->m_priority = nzbInfo->GetPriority(); + scriptController->m_dupeKey = strdup(nzbInfo->GetDupeKey()); + scriptController->m_dupeMode = nzbInfo->GetDupeMode(); + scriptController->m_dupeScore = nzbInfo->GetDupeScore(); + scriptController->m_parameters.CopyFrom(nzbInfo->GetParameters()); + scriptController->m_script = script; + scriptController->m_event = event; + scriptController->m_prefixLen = 0; + scriptController->m_markBad = false; + scriptController->m_deleteStatus = nzbInfo->GetDeleteStatus(); + scriptController->m_urlStatus = nzbInfo->GetUrlStatus(); + scriptController->SetAutoDestroy(true); - pScriptController->Start(); + scriptController->Start(); } void QueueScriptController::Run() { - ExecuteScript(m_pScript); + ExecuteScript(m_script); SetLogPrefix(NULL); - if (m_bMarkBad) + if (m_markBad) { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->Find(m_iID); - if (pNZBInfo) + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + NZBInfo* nzbInfo = downloadQueue->GetQueue()->Find(m_id); + if (nzbInfo) { - PrintMessage(Message::mkWarning, "Cancelling download and deleting %s", m_szNZBName); - pNZBInfo->SetDeleteStatus(NZBInfo::dsBad); - pDownloadQueue->EditEntry(m_iID, DownloadQueue::eaGroupDelete, 0, NULL); + PrintMessage(Message::mkWarning, "Cancelling download and deleting %s", m_nzbName); + nzbInfo->SetDeleteStatus(NZBInfo::dsBad); + downloadQueue->EditEntry(m_id, DownloadQueue::eaGroupDelete, 0, NULL); } DownloadQueue::Unlock(); } @@ -141,129 +141,129 @@ void QueueScriptController::Run() g_pQueueScriptCoordinator->CheckQueue(); } -void QueueScriptController::ExecuteScript(ScriptConfig::Script* pScript) +void QueueScriptController::ExecuteScript(ScriptConfig::Script* script) { - PrintMessage(m_eEvent == QueueScriptCoordinator::qeFileDownloaded ? Message::mkDetail : Message::mkInfo, - "Executing queue-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBName)); + PrintMessage(m_event == QueueScriptCoordinator::qeFileDownloaded ? Message::mkDetail : Message::mkInfo, + "Executing queue-script %s for %s", script->GetName(), Util::BaseFileName(m_nzbName)); - SetScript(pScript->GetLocation()); + SetScript(script->GetLocation()); SetArgs(NULL, false); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "queue-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBName)); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "queue-script %s for %s", script->GetName(), Util::BaseFileName(m_nzbName)); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - SetLogPrefix(pScript->GetDisplayName()); - m_iPrefixLen = strlen(pScript->GetDisplayName()) + 2; // 2 = strlen(": "); - PrepareParams(pScript->GetName()); + SetLogPrefix(script->GetDisplayName()); + m_prefixLen = strlen(script->GetDisplayName()) + 2; // 2 = strlen(": "); + PrepareParams(script->GetName()); Execute(); SetLogPrefix(NULL); } -void QueueScriptController::PrepareParams(const char* szScriptName) +void QueueScriptController::PrepareParams(const char* scriptName) { ResetEnv(); - SetEnvVar("NZBNA_NZBNAME", m_szNZBName); - SetIntEnvVar("NZBNA_NZBID", m_iID); - SetEnvVar("NZBNA_FILENAME", m_szNZBFilename); - SetEnvVar("NZBNA_DIRECTORY", m_szDestDir); - SetEnvVar("NZBNA_URL", m_szUrl); - SetEnvVar("NZBNA_CATEGORY", m_szCategory); - SetIntEnvVar("NZBNA_PRIORITY", m_iPriority); - SetIntEnvVar("NZBNA_LASTID", m_iID); // deprecated + SetEnvVar("NZBNA_NZBNAME", m_nzbName); + SetIntEnvVar("NZBNA_NZBID", m_id); + SetEnvVar("NZBNA_FILENAME", m_nzbFilename); + SetEnvVar("NZBNA_DIRECTORY", m_destDir); + SetEnvVar("NZBNA_URL", m_url); + SetEnvVar("NZBNA_CATEGORY", m_category); + SetIntEnvVar("NZBNA_PRIORITY", m_priority); + SetIntEnvVar("NZBNA_LASTID", m_id); // deprecated - SetEnvVar("NZBNA_DUPEKEY", m_szDupeKey); - SetIntEnvVar("NZBNA_DUPESCORE", m_iDupeScore); + SetEnvVar("NZBNA_DUPEKEY", m_dupeKey); + SetIntEnvVar("NZBNA_DUPESCORE", m_dupeScore); - const char* szDupeModeName[] = { "SCORE", "ALL", "FORCE" }; - SetEnvVar("NZBNA_DUPEMODE", szDupeModeName[m_eDupeMode]); + const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; + SetEnvVar("NZBNA_DUPEMODE", dupeModeName[m_dupeMode]); - SetEnvVar("NZBNA_EVENT", QUEUE_EVENT_NAMES[m_eEvent]); + SetEnvVar("NZBNA_EVENT", QUEUE_EVENT_NAMES[m_event]); - const char* szDeleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; - SetEnvVar("NZBNA_DELETESTATUS", szDeleteStatusName[m_eDeleteStatus]); + const char* deleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; + SetEnvVar("NZBNA_DELETESTATUS", deleteStatusName[m_deleteStatus]); - const char* szUrlStatusName[] = { "NONE", "UNKNOWN", "SUCCESS", "FAILURE", "UNKNOWN", "SCAN_SKIPPED", "SCAN_FAILURE" }; - SetEnvVar("NZBNA_URLSTATUS", szUrlStatusName[m_eUrlStatus]); + const char* urlStatusName[] = { "NONE", "UNKNOWN", "SUCCESS", "FAILURE", "UNKNOWN", "SCAN_SKIPPED", "SCAN_FAILURE" }; + SetEnvVar("NZBNA_URLSTATUS", urlStatusName[m_urlStatus]); - PrepareEnvScript(&m_Parameters, szScriptName); + PrepareEnvScript(&m_parameters, scriptName); } -void QueueScriptController::AddMessage(Message::EKind eKind, const char* szText) +void QueueScriptController::AddMessage(Message::EKind kind, const char* text) { - const char* szMsgText = szText + m_iPrefixLen; + const char* msgText = text + m_prefixLen; - if (!strncmp(szMsgText, "[NZB] ", 6)) + if (!strncmp(msgText, "[NZB] ", 6)) { - debug("Command %s detected", szMsgText + 6); - if (!strncmp(szMsgText + 6, "NZBPR_", 6)) + debug("Command %s detected", msgText + 6); + if (!strncmp(msgText + 6, "NZBPR_", 6)) { - char* szParam = strdup(szMsgText + 6 + 6); - char* szValue = strchr(szParam, '='); - if (szValue) + char* param = strdup(msgText + 6 + 6); + char* value = strchr(param, '='); + if (value) { - *szValue = '\0'; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->Find(m_iID); - if (pNZBInfo) + *value = '\0'; + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + NZBInfo* nzbInfo = downloadQueue->GetQueue()->Find(m_id); + if (nzbInfo) { - pNZBInfo->GetParameters()->SetParameter(szParam, szValue + 1); + nzbInfo->GetParameters()->SetParameter(param, value + 1); } DownloadQueue::Unlock(); } else { - error("Invalid command \"%s\" received from %s", szMsgText, GetInfoName()); + error("Invalid command \"%s\" received from %s", msgText, GetInfoName()); } - free(szParam); + free(param); } - else if (!strncmp(szMsgText + 6, "MARK=BAD", 8)) + else if (!strncmp(msgText + 6, "MARK=BAD", 8)) { - m_bMarkBad = true; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->Find(m_iID); - if (pNZBInfo) + m_markBad = true; + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + NZBInfo* nzbInfo = downloadQueue->GetQueue()->Find(m_id); + if (nzbInfo) { SetLogPrefix(NULL); - PrintMessage(Message::mkWarning, "Marking %s as bad", m_szNZBName); - SetLogPrefix(m_pScript->GetDisplayName()); - pNZBInfo->SetMarkStatus(NZBInfo::ksBad); + PrintMessage(Message::mkWarning, "Marking %s as bad", m_nzbName); + SetLogPrefix(m_script->GetDisplayName()); + nzbInfo->SetMarkStatus(NZBInfo::ksBad); } DownloadQueue::Unlock(); } else { - error("Invalid command \"%s\" received from %s", szMsgText, GetInfoName()); + error("Invalid command \"%s\" received from %s", msgText, GetInfoName()); } } else { - ScriptController::AddMessage(eKind, szText); + ScriptController::AddMessage(kind, text); } } -QueueScriptCoordinator::QueueItem::QueueItem(int iNZBID, ScriptConfig::Script* pScript, EEvent eEvent) +QueueScriptCoordinator::QueueItem::QueueItem(int nzbId, ScriptConfig::Script* script, EEvent event) { - m_iNZBID = iNZBID; - m_pScript = pScript; - m_eEvent = eEvent; + m_nzbId = nzbId; + m_script = script; + m_event = event; } QueueScriptCoordinator::QueueScriptCoordinator() { - m_pCurItem = NULL; - m_bStopped = false; + m_curItem = NULL; + m_stopped = false; } QueueScriptCoordinator::~QueueScriptCoordinator() { - delete m_pCurItem; - for (Queue::iterator it = m_Queue.begin(); it != m_Queue.end(); it++ ) + delete m_curItem; + for (Queue::iterator it = m_queue.begin(); it != m_queue.end(); it++ ) { delete *it; } @@ -271,37 +271,37 @@ QueueScriptCoordinator::~QueueScriptCoordinator() void QueueScriptCoordinator::InitOptions() { - m_bHasQueueScripts = false; + m_hasQueueScripts = false; for (ScriptConfig::Scripts::iterator it = g_pScriptConfig->GetScripts()->begin(); it != g_pScriptConfig->GetScripts()->end(); it++) { - ScriptConfig::Script* pScript = *it; - if (pScript->GetQueueScript()) + ScriptConfig::Script* script = *it; + if (script->GetQueueScript()) { - m_bHasQueueScripts = true; + m_hasQueueScripts = true; break; } } } -void QueueScriptCoordinator::EnqueueScript(NZBInfo* pNZBInfo, EEvent eEvent) +void QueueScriptCoordinator::EnqueueScript(NZBInfo* nzbInfo, EEvent event) { - if (!m_bHasQueueScripts) + if (!m_hasQueueScripts) { return; } - m_mutexQueue.Lock(); + m_queueMutex.Lock(); - if (eEvent == qeNzbDownloaded) + if (event == qeNzbDownloaded) { // delete all other queued scripts for this nzb - for (Queue::iterator it = m_Queue.begin(); it != m_Queue.end(); ) + for (Queue::iterator it = m_queue.begin(); it != m_queue.end(); ) { - QueueItem* pQueueItem = *it; - if (pQueueItem->GetNZBID() == pNZBInfo->GetID()) + QueueItem* queueItem = *it; + if (queueItem->GetNZBID() == nzbInfo->GetID()) { - delete pQueueItem; - it = m_Queue.erase(it); + delete queueItem; + it = m_queue.erase(it); continue; } it++; @@ -309,217 +309,217 @@ void QueueScriptCoordinator::EnqueueScript(NZBInfo* pNZBInfo, EEvent eEvent) } // respect option "EventInterval" - time_t tCurTime = time(NULL); - if (eEvent == qeFileDownloaded && + time_t curTime = time(NULL); + if (event == qeFileDownloaded && (g_pOptions->GetEventInterval() == -1 || - (g_pOptions->GetEventInterval() > 0 && tCurTime - pNZBInfo->GetQueueScriptTime() > 0 && - (int)(tCurTime - pNZBInfo->GetQueueScriptTime()) < g_pOptions->GetEventInterval()))) + (g_pOptions->GetEventInterval() > 0 && curTime - nzbInfo->GetQueueScriptTime() > 0 && + (int)(curTime - nzbInfo->GetQueueScriptTime()) < g_pOptions->GetEventInterval()))) { - m_mutexQueue.Unlock(); + m_queueMutex.Unlock(); return; } for (ScriptConfig::Scripts::iterator it = g_pScriptConfig->GetScripts()->begin(); it != g_pScriptConfig->GetScripts()->end(); it++) { - ScriptConfig::Script* pScript = *it; + ScriptConfig::Script* script = *it; - if (!pScript->GetQueueScript()) + if (!script->GetQueueScript()) { continue; } - bool bUseScript = false; + bool useScript = false; // check queue-scripts - const char* szQueueScript = g_pOptions->GetQueueScript(); - if (!Util::EmptyStr(szQueueScript)) + const char* queueScript = g_pOptions->GetQueueScript(); + if (!Util::EmptyStr(queueScript)) { // split szQueueScript into tokens - Tokenizer tok(szQueueScript, ",;"); - while (const char* szScriptName = tok.Next()) + Tokenizer tok(queueScript, ",;"); + while (const char* scriptName = tok.Next()) { - if (Util::SameFilename(szScriptName, pScript->GetName())) + if (Util::SameFilename(scriptName, script->GetName())) { - bUseScript = true; + useScript = true; break; } } } // check post-processing-scripts - if (!bUseScript) + if (!useScript) { - for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++) + for (NZBParameterList::iterator it = nzbInfo->GetParameters()->begin(); it != nzbInfo->GetParameters()->end(); it++) { - NZBParameter* pParameter = *it; - const char* szVarname = pParameter->GetName(); - if (strlen(szVarname) > 0 && szVarname[0] != '*' && szVarname[strlen(szVarname)-1] == ':' && - (!strcasecmp(pParameter->GetValue(), "yes") || - !strcasecmp(pParameter->GetValue(), "on") || - !strcasecmp(pParameter->GetValue(), "1"))) + NZBParameter* parameter = *it; + const char* varname = parameter->GetName(); + if (strlen(varname) > 0 && varname[0] != '*' && varname[strlen(varname)-1] == ':' && + (!strcasecmp(parameter->GetValue(), "yes") || + !strcasecmp(parameter->GetValue(), "on") || + !strcasecmp(parameter->GetValue(), "1"))) { - char szScriptName[1024]; - strncpy(szScriptName, szVarname, 1024); - szScriptName[1024-1] = '\0'; - szScriptName[strlen(szScriptName)-1] = '\0'; // remove trailing ':' - if (Util::SameFilename(szScriptName, pScript->GetName())) + char scriptName[1024]; + strncpy(scriptName, varname, 1024); + scriptName[1024-1] = '\0'; + scriptName[strlen(scriptName)-1] = '\0'; // remove trailing ':' + if (Util::SameFilename(scriptName, script->GetName())) { - bUseScript = true; + useScript = true; break; } } } } - bUseScript &= Util::EmptyStr(pScript->GetQueueEvents()) || strstr(pScript->GetQueueEvents(), QUEUE_EVENT_NAMES[eEvent]); + useScript &= Util::EmptyStr(script->GetQueueEvents()) || strstr(script->GetQueueEvents(), QUEUE_EVENT_NAMES[event]); - if (bUseScript) + if (useScript) { - bool bAlreadyQueued = false; - if (eEvent == qeFileDownloaded) + bool alreadyQueued = false; + if (event == qeFileDownloaded) { // check if this script is already queued for this nzb - for (Queue::iterator it2 = m_Queue.begin(); it2 != m_Queue.end(); it2++) + for (Queue::iterator it2 = m_queue.begin(); it2 != m_queue.end(); it2++) { - QueueItem* pQueueItem = *it2; - if (pQueueItem->GetNZBID() == pNZBInfo->GetID() && pQueueItem->GetScript() == pScript) + QueueItem* queueItem = *it2; + if (queueItem->GetNZBID() == nzbInfo->GetID() && queueItem->GetScript() == script) { - bAlreadyQueued = true; + alreadyQueued = true; break; } } } - if (!bAlreadyQueued) + if (!alreadyQueued) { - QueueItem* pQueueItem = new QueueItem(pNZBInfo->GetID(), pScript, eEvent); - if (m_pCurItem) + QueueItem* queueItem = new QueueItem(nzbInfo->GetID(), script, event); + if (m_curItem) { - m_Queue.push_back(pQueueItem); + m_queue.push_back(queueItem); } else { - StartScript(pNZBInfo, pQueueItem); + StartScript(nzbInfo, queueItem); } } - pNZBInfo->SetQueueScriptTime(time(NULL)); + nzbInfo->SetQueueScriptTime(time(NULL)); } } - m_mutexQueue.Unlock(); + m_queueMutex.Unlock(); } -NZBInfo* QueueScriptCoordinator::FindNZBInfo(DownloadQueue* pDownloadQueue, int iNZBID) +NZBInfo* QueueScriptCoordinator::FindNZBInfo(DownloadQueue* downloadQueue, int nzbId) { - NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->Find(iNZBID); - if (!pNZBInfo) + NZBInfo* nzbInfo = downloadQueue->GetQueue()->Find(nzbId); + if (!nzbInfo) { - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetNZBInfo() && pHistoryInfo->GetNZBInfo()->GetID() == iNZBID) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetNZBInfo() && historyInfo->GetNZBInfo()->GetID() == nzbId) { - pNZBInfo = pHistoryInfo->GetNZBInfo(); + nzbInfo = historyInfo->GetNZBInfo(); break; } } } - return pNZBInfo; + return nzbInfo; } void QueueScriptCoordinator::CheckQueue() { - if (m_bStopped) + if (m_stopped) { return; } - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - m_mutexQueue.Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + m_queueMutex.Lock(); - delete m_pCurItem; + delete m_curItem; - m_pCurItem = NULL; - NZBInfo* pCurNZBInfo = NULL; - Queue::iterator itCurItem = m_Queue.end(); + m_curItem = NULL; + NZBInfo* curNzbInfo = NULL; + Queue::iterator itCurItem = m_queue.end(); - for (Queue::iterator it = m_Queue.begin(); it != m_Queue.end(); ) + for (Queue::iterator it = m_queue.begin(); it != m_queue.end(); ) { - QueueItem* pQueueItem = *it; + QueueItem* queueItem = *it; - NZBInfo* pNZBInfo = FindNZBInfo(pDownloadQueue, pQueueItem->GetNZBID()); + NZBInfo* nzbInfo = FindNZBInfo(downloadQueue, queueItem->GetNZBID()); // in a case this nzb must not be processed further - delete queue script from queue - if (!pNZBInfo || - (pNZBInfo->GetDeleteStatus() != NZBInfo::dsNone && pQueueItem->GetEvent() != qeNzbDeleted) || - pNZBInfo->GetMarkStatus() == NZBInfo::ksBad) + if (!nzbInfo || + (nzbInfo->GetDeleteStatus() != NZBInfo::dsNone && queueItem->GetEvent() != qeNzbDeleted) || + nzbInfo->GetMarkStatus() == NZBInfo::ksBad) { - delete pQueueItem; - it = m_Queue.erase(it); + delete queueItem; + it = m_queue.erase(it); continue; } - if (!m_pCurItem || pQueueItem->GetEvent() > m_pCurItem->GetEvent()) + if (!m_curItem || queueItem->GetEvent() > m_curItem->GetEvent()) { - m_pCurItem = pQueueItem; + m_curItem = queueItem; itCurItem = it; - pCurNZBInfo = pNZBInfo; + curNzbInfo = nzbInfo; } it++; } - if (m_pCurItem) + if (m_curItem) { - m_Queue.erase(itCurItem); - StartScript(pCurNZBInfo, m_pCurItem); + m_queue.erase(itCurItem); + StartScript(curNzbInfo, m_curItem); } - m_mutexQueue.Unlock(); + m_queueMutex.Unlock(); DownloadQueue::Unlock(); } -void QueueScriptCoordinator::StartScript(NZBInfo* pNZBInfo, QueueItem* pQueueItem) +void QueueScriptCoordinator::StartScript(NZBInfo* nzbInfo, QueueItem* queueItem) { - m_pCurItem = pQueueItem; - QueueScriptController::StartScript(pNZBInfo, pQueueItem->GetScript(), pQueueItem->GetEvent()); + m_curItem = queueItem; + QueueScriptController::StartScript(nzbInfo, queueItem->GetScript(), queueItem->GetEvent()); } -bool QueueScriptCoordinator::HasJob(int iNZBID, bool* pActive) +bool QueueScriptCoordinator::HasJob(int nzbId, bool* active) { - m_mutexQueue.Lock(); - bool bWorking = m_pCurItem && m_pCurItem->GetNZBID() == iNZBID; - if (pActive) + m_queueMutex.Lock(); + bool working = m_curItem && m_curItem->GetNZBID() == nzbId; + if (active) { - *pActive = bWorking; + *active = working; } - if (!bWorking) + if (!working) { - for (Queue::iterator it = m_Queue.begin(); it != m_Queue.end(); it++) + for (Queue::iterator it = m_queue.begin(); it != m_queue.end(); it++) { - QueueItem* pQueueItem = *it; - bWorking = pQueueItem->GetNZBID() == iNZBID; - if (bWorking) + QueueItem* queueItem = *it; + working = queueItem->GetNZBID() == nzbId; + if (working) { break; } } } - m_mutexQueue.Unlock(); + m_queueMutex.Unlock(); - return bWorking; + return working; } int QueueScriptCoordinator::GetQueueSize() { - m_mutexQueue.Lock(); - int iQueuedCount = m_Queue.size(); - if (m_pCurItem) + m_queueMutex.Lock(); + int queuedCount = m_queue.size(); + if (m_curItem) { - iQueuedCount++; + queuedCount++; } - m_mutexQueue.Unlock(); + m_queueMutex.Unlock(); - return iQueuedCount; + return queuedCount; } diff --git a/daemon/extension/QueueScript.h b/daemon/extension/QueueScript.h index a3d75435..4948e1a6 100644 --- a/daemon/extension/QueueScript.h +++ b/daemon/extension/QueueScript.h @@ -47,35 +47,35 @@ private: class QueueItem { private: - int m_iNZBID; - ScriptConfig::Script* m_pScript; - EEvent m_eEvent; + int m_nzbId; + ScriptConfig::Script* m_script; + EEvent m_event; public: - QueueItem(int iNZBID, ScriptConfig::Script* pScript, EEvent eEvent); - int GetNZBID() { return m_iNZBID; } - ScriptConfig::Script* GetScript() { return m_pScript; } - EEvent GetEvent() { return m_eEvent; } + QueueItem(int nzbId, ScriptConfig::Script* script, EEvent event); + int GetNZBID() { return m_nzbId; } + ScriptConfig::Script* GetScript() { return m_script; } + EEvent GetEvent() { return m_event; } }; typedef std::list Queue; - Queue m_Queue; - Mutex m_mutexQueue; - QueueItem* m_pCurItem; - bool m_bHasQueueScripts; - bool m_bStopped; + Queue m_queue; + Mutex m_queueMutex; + QueueItem* m_curItem; + bool m_hasQueueScripts; + bool m_stopped; - void StartScript(NZBInfo* pNZBInfo, QueueItem* pQueueItem); - NZBInfo* FindNZBInfo(DownloadQueue* pDownloadQueue, int iNZBID); + void StartScript(NZBInfo* nzbInfo, QueueItem* queueItem); + NZBInfo* FindNZBInfo(DownloadQueue* downloadQueue, int nzbId); public: QueueScriptCoordinator(); ~QueueScriptCoordinator(); - void Stop() { m_bStopped = true; } + void Stop() { m_stopped = true; } void InitOptions(); - void EnqueueScript(NZBInfo* pNZBInfo, EEvent eEvent); + void EnqueueScript(NZBInfo* nzbInfo, EEvent event); void CheckQueue(); - bool HasJob(int iNZBID, bool* pActive); + bool HasJob(int nzbId, bool* active); int GetQueueSize(); }; diff --git a/daemon/extension/ScanScript.cpp b/daemon/extension/ScanScript.cpp index 178b3fe7..8ed1ec7d 100644 --- a/daemon/extension/ScanScript.cpp +++ b/daemon/extension/ScanScript.cpp @@ -47,161 +47,161 @@ #include "Log.h" #include "Util.h" -void ScanScriptController::ExecuteScripts(const char* szNZBFilename, - const char* szUrl, const char* szDirectory, char** pNZBName, char** pCategory, - int* iPriority, NZBParameterList* pParameters, bool* bAddTop, bool* bAddPaused, - char** pDupeKey, int* iDupeScore, EDupeMode* eDupeMode) +void ScanScriptController::ExecuteScripts(const char* nzbFilename, + const char* url, const char* directory, char** nzbName, char** category, + int* priority, NZBParameterList* parameters, bool* addTop, bool* addPaused, + char** dupeKey, int* dupeScore, EDupeMode* dupeMode) { - ScanScriptController* pScriptController = new ScanScriptController(); + ScanScriptController* scriptController = new ScanScriptController(); - pScriptController->m_szNZBFilename = szNZBFilename; - pScriptController->m_szUrl = szUrl; - pScriptController->m_szDirectory = szDirectory; - pScriptController->m_pNZBName = pNZBName; - pScriptController->m_pCategory = pCategory; - pScriptController->m_pParameters = pParameters; - pScriptController->m_iPriority = iPriority; - pScriptController->m_bAddTop = bAddTop; - pScriptController->m_bAddPaused = bAddPaused; - pScriptController->m_pDupeKey = pDupeKey; - pScriptController->m_iDupeScore = iDupeScore; - pScriptController->m_eDupeMode = eDupeMode; - pScriptController->m_iPrefixLen = 0; + scriptController->m_nzbFilename = nzbFilename; + scriptController->m_url = url; + scriptController->m_directory = directory; + scriptController->m_nzbName = nzbName; + scriptController->m_category = category; + scriptController->m_parameters = parameters; + scriptController->m_priority = priority; + scriptController->m_addTop = addTop; + scriptController->m_addPaused = addPaused; + scriptController->m_dupeKey = dupeKey; + scriptController->m_dupeScore = dupeScore; + scriptController->m_dupeMode = dupeMode; + scriptController->m_prefixLen = 0; - pScriptController->ExecuteScriptList(g_pOptions->GetScanScript()); + scriptController->ExecuteScriptList(g_pOptions->GetScanScript()); - delete pScriptController; + delete scriptController; } -void ScanScriptController::ExecuteScript(ScriptConfig::Script* pScript) +void ScanScriptController::ExecuteScript(ScriptConfig::Script* script) { - if (!pScript->GetScanScript() || !Util::FileExists(m_szNZBFilename)) + if (!script->GetScanScript() || !Util::FileExists(m_nzbFilename)) { return; } - PrintMessage(Message::mkInfo, "Executing scan-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBFilename)); + PrintMessage(Message::mkInfo, "Executing scan-script %s for %s", script->GetName(), Util::BaseFileName(m_nzbFilename)); - SetScript(pScript->GetLocation()); + SetScript(script->GetLocation()); SetArgs(NULL, false); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "scan-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBFilename)); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "scan-script %s for %s", script->GetName(), Util::BaseFileName(m_nzbFilename)); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - SetLogPrefix(pScript->GetDisplayName()); - m_iPrefixLen = strlen(pScript->GetDisplayName()) + 2; // 2 = strlen(": "); - PrepareParams(pScript->GetName()); + SetLogPrefix(script->GetDisplayName()); + m_prefixLen = strlen(script->GetDisplayName()) + 2; // 2 = strlen(": "); + PrepareParams(script->GetName()); Execute(); SetLogPrefix(NULL); } -void ScanScriptController::PrepareParams(const char* szScriptName) +void ScanScriptController::PrepareParams(const char* scriptName) { ResetEnv(); - SetEnvVar("NZBNP_FILENAME", m_szNZBFilename); - SetEnvVar("NZBNP_URL", m_szUrl); - SetEnvVar("NZBNP_NZBNAME", strlen(*m_pNZBName) > 0 ? *m_pNZBName : Util::BaseFileName(m_szNZBFilename)); - SetEnvVar("NZBNP_CATEGORY", *m_pCategory); - SetIntEnvVar("NZBNP_PRIORITY", *m_iPriority); - SetIntEnvVar("NZBNP_TOP", *m_bAddTop ? 1 : 0); - SetIntEnvVar("NZBNP_PAUSED", *m_bAddPaused ? 1 : 0); - SetEnvVar("NZBNP_DUPEKEY", *m_pDupeKey); - SetIntEnvVar("NZBNP_DUPESCORE", *m_iDupeScore); + SetEnvVar("NZBNP_FILENAME", m_nzbFilename); + SetEnvVar("NZBNP_URL", m_url); + SetEnvVar("NZBNP_NZBNAME", strlen(*m_nzbName) > 0 ? *m_nzbName : Util::BaseFileName(m_nzbFilename)); + SetEnvVar("NZBNP_CATEGORY", *m_category); + SetIntEnvVar("NZBNP_PRIORITY", *m_priority); + SetIntEnvVar("NZBNP_TOP", *m_addTop ? 1 : 0); + SetIntEnvVar("NZBNP_PAUSED", *m_addPaused ? 1 : 0); + SetEnvVar("NZBNP_DUPEKEY", *m_dupeKey); + SetIntEnvVar("NZBNP_DUPESCORE", *m_dupeScore); - const char* szDupeModeName[] = { "SCORE", "ALL", "FORCE" }; - SetEnvVar("NZBNP_DUPEMODE", szDupeModeName[*m_eDupeMode]); + const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; + SetEnvVar("NZBNP_DUPEMODE", dupeModeName[*m_dupeMode]); // remove trailing slash - char szDir[1024]; - strncpy(szDir, m_szDirectory, 1024); - szDir[1024-1] = '\0'; - int iLen = strlen(szDir); - if (szDir[iLen-1] == PATH_SEPARATOR) + char dir[1024]; + strncpy(dir, m_directory, 1024); + dir[1024-1] = '\0'; + int len = strlen(dir); + if (dir[len-1] == PATH_SEPARATOR) { - szDir[iLen-1] = '\0'; + dir[len-1] = '\0'; } - SetEnvVar("NZBNP_DIRECTORY", szDir); + SetEnvVar("NZBNP_DIRECTORY", dir); - PrepareEnvScript(m_pParameters, szScriptName); + PrepareEnvScript(m_parameters, scriptName); } -void ScanScriptController::AddMessage(Message::EKind eKind, const char* szText) +void ScanScriptController::AddMessage(Message::EKind kind, const char* text) { - const char* szMsgText = szText + m_iPrefixLen; + const char* msgText = text + m_prefixLen; - if (!strncmp(szMsgText, "[NZB] ", 6)) + if (!strncmp(msgText, "[NZB] ", 6)) { - debug("Command %s detected", szMsgText + 6); - if (!strncmp(szMsgText + 6, "NZBNAME=", 8)) + debug("Command %s detected", msgText + 6); + if (!strncmp(msgText + 6, "NZBNAME=", 8)) { - free(*m_pNZBName); - *m_pNZBName = strdup(szMsgText + 6 + 8); + free(*m_nzbName); + *m_nzbName = strdup(msgText + 6 + 8); } - else if (!strncmp(szMsgText + 6, "CATEGORY=", 9)) + else if (!strncmp(msgText + 6, "CATEGORY=", 9)) { - free(*m_pCategory); - *m_pCategory = strdup(szMsgText + 6 + 9); - g_pScanner->InitPPParameters(*m_pCategory, m_pParameters, true); + free(*m_category); + *m_category = strdup(msgText + 6 + 9); + g_pScanner->InitPPParameters(*m_category, m_parameters, true); } - else if (!strncmp(szMsgText + 6, "NZBPR_", 6)) + else if (!strncmp(msgText + 6, "NZBPR_", 6)) { - char* szParam = strdup(szMsgText + 6 + 6); - char* szValue = strchr(szParam, '='); - if (szValue) + char* param = strdup(msgText + 6 + 6); + char* value = strchr(param, '='); + if (value) { - *szValue = '\0'; - m_pParameters->SetParameter(szParam, szValue + 1); + *value = '\0'; + m_parameters->SetParameter(param, value + 1); } else { - error("Invalid command \"%s\" received from %s", szMsgText, GetInfoName()); + error("Invalid command \"%s\" received from %s", msgText, GetInfoName()); } - free(szParam); + free(param); } - else if (!strncmp(szMsgText + 6, "PRIORITY=", 9)) + else if (!strncmp(msgText + 6, "PRIORITY=", 9)) { - *m_iPriority = atoi(szMsgText + 6 + 9); + *m_priority = atoi(msgText + 6 + 9); } - else if (!strncmp(szMsgText + 6, "TOP=", 4)) + else if (!strncmp(msgText + 6, "TOP=", 4)) { - *m_bAddTop = atoi(szMsgText + 6 + 4) != 0; + *m_addTop = atoi(msgText + 6 + 4) != 0; } - else if (!strncmp(szMsgText + 6, "PAUSED=", 7)) + else if (!strncmp(msgText + 6, "PAUSED=", 7)) { - *m_bAddPaused = atoi(szMsgText + 6 + 7) != 0; + *m_addPaused = atoi(msgText + 6 + 7) != 0; } - else if (!strncmp(szMsgText + 6, "DUPEKEY=", 8)) + else if (!strncmp(msgText + 6, "DUPEKEY=", 8)) { - free(*m_pDupeKey); - *m_pDupeKey = strdup(szMsgText + 6 + 8); + free(*m_dupeKey); + *m_dupeKey = strdup(msgText + 6 + 8); } - else if (!strncmp(szMsgText + 6, "DUPESCORE=", 10)) + else if (!strncmp(msgText + 6, "DUPESCORE=", 10)) { - *m_iDupeScore = atoi(szMsgText + 6 + 10); + *m_dupeScore = atoi(msgText + 6 + 10); } - else if (!strncmp(szMsgText + 6, "DUPEMODE=", 9)) + else if (!strncmp(msgText + 6, "DUPEMODE=", 9)) { - const char* szDupeMode = szMsgText + 6 + 9; - if (strcasecmp(szDupeMode, "score") && strcasecmp(szDupeMode, "all") && strcasecmp(szDupeMode, "force")) + const char* dupeMode = msgText + 6 + 9; + if (strcasecmp(dupeMode, "score") && strcasecmp(dupeMode, "all") && strcasecmp(dupeMode, "force")) { - error("Invalid value \"%s\" for command \"DUPEMODE\" received from %s", szDupeMode, GetInfoName()); + error("Invalid value \"%s\" for command \"DUPEMODE\" received from %s", dupeMode, GetInfoName()); return; } - *m_eDupeMode = !strcasecmp(szDupeMode, "all") ? dmAll : - !strcasecmp(szDupeMode, "force") ? dmForce : dmScore; + *m_dupeMode = !strcasecmp(dupeMode, "all") ? dmAll : + !strcasecmp(dupeMode, "force") ? dmForce : dmScore; } else { - error("Invalid command \"%s\" received from %s", szMsgText, GetInfoName()); + error("Invalid command \"%s\" received from %s", msgText, GetInfoName()); } } else { - ScriptController::AddMessage(eKind, szText); + ScriptController::AddMessage(kind, text); } } diff --git a/daemon/extension/ScanScript.h b/daemon/extension/ScanScript.h index 96c3374a..f6e82557 100644 --- a/daemon/extension/ScanScript.h +++ b/daemon/extension/ScanScript.h @@ -31,31 +31,31 @@ class ScanScriptController : public NZBScriptController { private: - const char* m_szNZBFilename; - const char* m_szUrl; - const char* m_szDirectory; - char** m_pNZBName; - char** m_pCategory; - int* m_iPriority; - NZBParameterList* m_pParameters; - bool* m_bAddTop; - bool* m_bAddPaused; - char** m_pDupeKey; - int* m_iDupeScore; - EDupeMode* m_eDupeMode; - int m_iPrefixLen; + const char* m_nzbFilename; + const char* m_url; + const char* m_directory; + char** m_nzbName; + char** m_category; + int* m_priority; + NZBParameterList* m_parameters; + bool* m_addTop; + bool* m_addPaused; + char** m_dupeKey; + int* m_dupeScore; + EDupeMode* m_dupeMode; + int m_prefixLen; - void PrepareParams(const char* szScriptName); + void PrepareParams(const char* scriptName); protected: - virtual void ExecuteScript(ScriptConfig::Script* pScript); - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void ExecuteScript(ScriptConfig::Script* script); + virtual void AddMessage(Message::EKind kind, const char* text); public: - static void ExecuteScripts(const char* szNZBFilename, const char* szUrl, - const char* szDirectory, char** pNZBName, char** pCategory, int* iPriority, - NZBParameterList* pParameters, bool* bAddTop, bool* bAddPaused, - char** pDupeKey, int* iDupeScore, EDupeMode* eDupeMode); + static void ExecuteScripts(const char* nzbFilename, const char* url, + const char* directory, char** nzbName, char** category, int* priority, + NZBParameterList* parameters, bool* addTop, bool* addPaused, + char** dupeKey, int* dupeScore, EDupeMode* dupeMode); }; #endif diff --git a/daemon/extension/SchedulerScript.cpp b/daemon/extension/SchedulerScript.cpp index 71ac8be8..0f292234 100644 --- a/daemon/extension/SchedulerScript.cpp +++ b/daemon/extension/SchedulerScript.cpp @@ -49,95 +49,95 @@ SchedulerScriptController::~SchedulerScriptController() { - free(m_szScript); + free(m_script); } -void SchedulerScriptController::StartScript(const char* szParam, bool bExternalProcess, int iTaskID) +void SchedulerScriptController::StartScript(const char* param, bool externalProcess, int taskId) { char** argv = NULL; - if (bExternalProcess && !Util::SplitCommandLine(szParam, &argv)) + if (externalProcess && !Util::SplitCommandLine(param, &argv)) { - error("Could not execute scheduled process-script, failed to parse command line: %s", szParam); + error("Could not execute scheduled process-script, failed to parse command line: %s", param); return; } - SchedulerScriptController* pScriptController = new SchedulerScriptController(); + SchedulerScriptController* scriptController = new SchedulerScriptController(); - pScriptController->m_bExternalProcess = bExternalProcess; - pScriptController->m_szScript = strdup(szParam); - pScriptController->m_iTaskID = iTaskID; + scriptController->m_externalProcess = externalProcess; + scriptController->m_script = strdup(param); + scriptController->m_taskId = taskId; - if (bExternalProcess) + if (externalProcess) { - pScriptController->SetScript(argv[0]); - pScriptController->SetArgs((const char**)argv, true); + scriptController->SetScript(argv[0]); + scriptController->SetArgs((const char**)argv, true); } - pScriptController->SetAutoDestroy(true); + scriptController->SetAutoDestroy(true); - pScriptController->Start(); + scriptController->Start(); } void SchedulerScriptController::Run() { - if (m_bExternalProcess) + if (m_externalProcess) { ExecuteExternalProcess(); } else { - ExecuteScriptList(m_szScript); + ExecuteScriptList(m_script); } } -void SchedulerScriptController::ExecuteScript(ScriptConfig::Script* pScript) +void SchedulerScriptController::ExecuteScript(ScriptConfig::Script* script) { - if (!pScript->GetSchedulerScript()) + if (!script->GetSchedulerScript()) { return; } - PrintMessage(Message::mkInfo, "Executing scheduler-script %s for Task%i", pScript->GetName(), m_iTaskID); + PrintMessage(Message::mkInfo, "Executing scheduler-script %s for Task%i", script->GetName(), m_taskId); - SetScript(pScript->GetLocation()); + SetScript(script->GetLocation()); SetArgs(NULL, false); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "scheduler-script %s for Task%i", pScript->GetName(), m_iTaskID); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "scheduler-script %s for Task%i", script->GetName(), m_taskId); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - SetLogPrefix(pScript->GetDisplayName()); - PrepareParams(pScript->GetName()); + SetLogPrefix(script->GetDisplayName()); + PrepareParams(script->GetName()); Execute(); SetLogPrefix(NULL); } -void SchedulerScriptController::PrepareParams(const char* szScriptName) +void SchedulerScriptController::PrepareParams(const char* scriptName) { ResetEnv(); - SetIntEnvVar("NZBSP_TASKID", m_iTaskID); + SetIntEnvVar("NZBSP_TASKID", m_taskId); - PrepareEnvScript(NULL, szScriptName); + PrepareEnvScript(NULL, scriptName); } void SchedulerScriptController::ExecuteExternalProcess() { - info("Executing scheduled process-script %s for Task%i", Util::BaseFileName(GetScript()), m_iTaskID); + info("Executing scheduled process-script %s for Task%i", Util::BaseFileName(GetScript()), m_taskId); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "scheduled process-script %s for Task%i", Util::BaseFileName(GetScript()), m_iTaskID); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "scheduled process-script %s for Task%i", Util::BaseFileName(GetScript()), m_taskId); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - char szLogPrefix[1024]; - strncpy(szLogPrefix, Util::BaseFileName(GetScript()), 1024); - szLogPrefix[1024-1] = '\0'; - if (char* ext = strrchr(szLogPrefix, '.')) *ext = '\0'; // strip file extension - SetLogPrefix(szLogPrefix); + char logPrefix[1024]; + strncpy(logPrefix, Util::BaseFileName(GetScript()), 1024); + logPrefix[1024-1] = '\0'; + if (char* ext = strrchr(logPrefix, '.')) *ext = '\0'; // strip file extension + SetLogPrefix(logPrefix); Execute(); } diff --git a/daemon/extension/SchedulerScript.h b/daemon/extension/SchedulerScript.h index 3a53ecb2..58320a3f 100644 --- a/daemon/extension/SchedulerScript.h +++ b/daemon/extension/SchedulerScript.h @@ -31,20 +31,20 @@ class SchedulerScriptController : public Thread, public NZBScriptController { private: - char* m_szScript; - bool m_bExternalProcess; - int m_iTaskID; + char* m_script; + bool m_externalProcess; + int m_taskId; - void PrepareParams(const char* szScriptName); + void PrepareParams(const char* scriptName); void ExecuteExternalProcess(); protected: - virtual void ExecuteScript(ScriptConfig::Script* pScript); + virtual void ExecuteScript(ScriptConfig::Script* script); public: virtual ~SchedulerScriptController(); virtual void Run(); - static void StartScript(const char* szParam, bool bExternalProcess, int iTaskID); + static void StartScript(const char* param, bool externalProcess, int taskId); }; #endif diff --git a/daemon/extension/ScriptConfig.cpp b/daemon/extension/ScriptConfig.cpp index d2aaa286..9ad7b77d 100644 --- a/daemon/extension/ScriptConfig.cpp +++ b/daemon/extension/ScriptConfig.cpp @@ -56,16 +56,16 @@ static const char* QUEUE_EVENTS_SIGNATURE = "### QUEUE EVENTS:"; ScriptConfig* g_pScriptConfig = NULL; -ScriptConfig::ConfigTemplate::ConfigTemplate(Script* pScript, const char* szTemplate) +ScriptConfig::ConfigTemplate::ConfigTemplate(Script* script, const char* templ) { - m_pScript = pScript; - m_szTemplate = strdup(szTemplate ? szTemplate : ""); + m_script = script; + m_template = strdup(templ ? templ : ""); } ScriptConfig::ConfigTemplate::~ConfigTemplate() { - delete m_pScript; - free(m_szTemplate); + delete m_script; + free(m_template); } ScriptConfig::ConfigTemplates::~ConfigTemplates() @@ -77,37 +77,37 @@ ScriptConfig::ConfigTemplates::~ConfigTemplates() } -ScriptConfig::Script::Script(const char* szName, const char* szLocation) +ScriptConfig::Script::Script(const char* name, const char* location) { - m_szName = strdup(szName); - m_szLocation = strdup(szLocation); - m_szDisplayName = strdup(szName); - m_bPostScript = false; - m_bScanScript = false; - m_bQueueScript = false; - m_bSchedulerScript = false; - m_bFeedScript = false; - m_szQueueEvents = NULL; + m_name = strdup(name); + m_location = strdup(location); + m_displayName = strdup(name); + m_postScript = false; + m_scanScript = false; + m_queueScript = false; + m_schedulerScript = false; + m_feedScript = false; + m_queueEvents = NULL; } ScriptConfig::Script::~Script() { - free(m_szName); - free(m_szLocation); - free(m_szDisplayName); - free(m_szQueueEvents); + free(m_name); + free(m_location); + free(m_displayName); + free(m_queueEvents); } -void ScriptConfig::Script::SetDisplayName(const char* szDisplayName) +void ScriptConfig::Script::SetDisplayName(const char* displayName) { - free(m_szDisplayName); - m_szDisplayName = strdup(szDisplayName); + free(m_displayName); + m_displayName = strdup(displayName); } -void ScriptConfig::Script::SetQueueEvents(const char* szQueueEvents) +void ScriptConfig::Script::SetQueueEvents(const char* queueEvents) { - free(m_szQueueEvents); - m_szQueueEvents = szQueueEvents ? strdup(szQueueEvents) : NULL; + free(m_queueEvents); + m_queueEvents = queueEvents ? strdup(queueEvents) : NULL; } @@ -125,14 +125,14 @@ void ScriptConfig::Scripts::Clear() clear(); } -ScriptConfig::Script* ScriptConfig::Scripts::Find(const char* szName) +ScriptConfig::Script* ScriptConfig::Scripts::Find(const char* name) { for (iterator it = begin(); it != end(); it++) { - Script* pScript = *it; - if (!strcmp(pScript->GetName(), szName)) + Script* script = *it; + if (!strcmp(script->GetName(), name)) { - return pScript; + return script; } } @@ -150,7 +150,7 @@ ScriptConfig::~ScriptConfig() { } -bool ScriptConfig::LoadConfig(Options::OptEntries* pOptEntries) +bool ScriptConfig::LoadConfig(Options::OptEntries* optEntries) { // read config file FILE* infile = fopen(g_pOptions->GetConfigFilename(), FOPEN_RB); @@ -160,10 +160,10 @@ bool ScriptConfig::LoadConfig(Options::OptEntries* pOptEntries) return false; } - int iBufLen = (int)Util::FileSize(g_pOptions->GetConfigFilename()) + 1; - char* buf = (char*)malloc(iBufLen); + int bufLen = (int)Util::FileSize(g_pOptions->GetConfigFilename()) + 1; + char* buf = (char*)malloc(bufLen); - while (fgets(buf, iBufLen - 1, infile)) + while (fgets(buf, bufLen - 1, infile)) { // remove trailing '\n' and '\r' and spaces Util::TrimRight(buf); @@ -178,10 +178,10 @@ bool ScriptConfig::LoadConfig(Options::OptEntries* pOptEntries) char* optvalue; if (g_pOptions->SplitOptionString(buf, &optname, &optvalue)) { - Options::OptEntry* pOptEntry = new Options::OptEntry(); - pOptEntry->SetName(optname); - pOptEntry->SetValue(optvalue); - pOptEntries->push_back(pOptEntry); + Options::OptEntry* optEntry = new Options::OptEntry(); + optEntry->SetName(optname); + optEntry->SetValue(optvalue); + optEntries->push_back(optEntry); free(optname); free(optvalue); @@ -194,7 +194,7 @@ bool ScriptConfig::LoadConfig(Options::OptEntries* pOptEntries) return true; } -bool ScriptConfig::SaveConfig(Options::OptEntries* pOptEntries) +bool ScriptConfig::SaveConfig(Options::OptEntries* optEntries) { // save to config file FILE* infile = fopen(g_pOptions->GetConfigFilename(), FOPEN_RBP); @@ -208,9 +208,9 @@ bool ScriptConfig::SaveConfig(Options::OptEntries* pOptEntries) std::set writtenOptions; // read config file into memory array - int iBufLen = (int)Util::FileSize(g_pOptions->GetConfigFilename()) + 1; - char* buf = (char*)malloc(iBufLen); - while (fgets(buf, iBufLen - 1, infile)) + int bufLen = (int)Util::FileSize(g_pOptions->GetConfigFilename()) + 1; + char* buf = (char*)malloc(bufLen); + while (fgets(buf, bufLen - 1, infile)) { config.push_back(strdup(buf)); } @@ -232,14 +232,14 @@ bool ScriptConfig::SaveConfig(Options::OptEntries* pOptEntries) char* optvalue; if (g_pOptions->SplitOptionString(buf, &optname, &optvalue)) { - Options::OptEntry *pOptEntry = pOptEntries->FindOption(optname); - if (pOptEntry) + Options::OptEntry *optEntry = optEntries->FindOption(optname); + if (optEntry) { - fputs(pOptEntry->GetName(), infile); + fputs(optEntry->GetName(), infile); fputs("=", infile); - fputs(pOptEntry->GetValue(), infile); + fputs(optEntry->GetValue(), infile); fputs("\n", infile); - writtenOptions.insert(pOptEntry); + writtenOptions.insert(optEntry); } free(optname); @@ -255,15 +255,15 @@ bool ScriptConfig::SaveConfig(Options::OptEntries* pOptEntries) } // write new options - for (Options::OptEntries::iterator it = pOptEntries->begin(); it != pOptEntries->end(); it++) + for (Options::OptEntries::iterator it = optEntries->begin(); it != optEntries->end(); it++) { - Options::OptEntry* pOptEntry = *it; - std::set::iterator fit = writtenOptions.find(pOptEntry); + Options::OptEntry* optEntry = *it; + std::set::iterator fit = writtenOptions.find(optEntry); if (fit == writtenOptions.end()) { - fputs(pOptEntry->GetName(), infile); + fputs(optEntry->GetName(), infile); fputs("=", infile); - fputs(pOptEntry->GetValue(), infile); + fputs(optEntry->GetValue(), infile); fputs("\n", infile); } } @@ -277,17 +277,17 @@ bool ScriptConfig::SaveConfig(Options::OptEntries* pOptEntries) return true; } -bool ScriptConfig::LoadConfigTemplates(ConfigTemplates* pConfigTemplates) +bool ScriptConfig::LoadConfigTemplates(ConfigTemplates* configTemplates) { - char* szBuffer; - int iLength; - if (!Util::LoadFileIntoBuffer(g_pOptions->GetConfigTemplate(), &szBuffer, &iLength)) + char* buffer; + int length; + if (!Util::LoadFileIntoBuffer(g_pOptions->GetConfigTemplate(), &buffer, &length)) { return false; } - ConfigTemplate* pConfigTemplate = new ConfigTemplate(NULL, szBuffer); - pConfigTemplates->push_back(pConfigTemplate); - free(szBuffer); + ConfigTemplate* configTemplate = new ConfigTemplate(NULL, buffer); + configTemplates->push_back(configTemplate); + free(buffer); if (!g_pOptions->GetScriptDir()) { @@ -297,28 +297,28 @@ bool ScriptConfig::LoadConfigTemplates(ConfigTemplates* pConfigTemplates) Scripts scriptList; LoadScripts(&scriptList); - const int iBeginSignatureLen = strlen(BEGIN_SCRIPT_SIGNATURE); - const int iQueueEventsSignatureLen = strlen(QUEUE_EVENTS_SIGNATURE); + const int beginSignatureLen = strlen(BEGIN_SCRIPT_SIGNATURE); + const int queueEventsSignatureLen = strlen(QUEUE_EVENTS_SIGNATURE); for (Scripts::iterator it = scriptList.begin(); it != scriptList.end(); it++) { - Script* pScript = *it; + Script* script = *it; - FILE* infile = fopen(pScript->GetLocation(), FOPEN_RB); + FILE* infile = fopen(script->GetLocation(), FOPEN_RB); if (!infile) { - ConfigTemplate* pConfigTemplate = new ConfigTemplate(pScript, ""); - pConfigTemplates->push_back(pConfigTemplate); + ConfigTemplate* configTemplate = new ConfigTemplate(script, ""); + configTemplates->push_back(configTemplate); continue; } StringBuilder stringBuilder; char buf[1024]; - bool bInConfig = false; + bool inConfig = false; while (fgets(buf, sizeof(buf) - 1, infile)) { - if (!strncmp(buf, BEGIN_SCRIPT_SIGNATURE, iBeginSignatureLen) && + if (!strncmp(buf, BEGIN_SCRIPT_SIGNATURE, beginSignatureLen) && strstr(buf, END_SCRIPT_SIGNATURE) && (strstr(buf, POST_SCRIPT_SIGNATURE) || strstr(buf, SCAN_SCRIPT_SIGNATURE) || @@ -326,17 +326,17 @@ bool ScriptConfig::LoadConfigTemplates(ConfigTemplates* pConfigTemplates) strstr(buf, SCHEDULER_SCRIPT_SIGNATURE) || strstr(buf, FEED_SCRIPT_SIGNATURE))) { - if (bInConfig) + if (inConfig) { break; } - bInConfig = true; + inConfig = true; continue; } - bool bSkip = !strncmp(buf, QUEUE_EVENTS_SIGNATURE, iQueueEventsSignatureLen); + bool skip = !strncmp(buf, QUEUE_EVENTS_SIGNATURE, queueEventsSignatureLen); - if (bInConfig && !bSkip) + if (inConfig && !skip) { stringBuilder.Append(buf); } @@ -344,8 +344,8 @@ bool ScriptConfig::LoadConfigTemplates(ConfigTemplates* pConfigTemplates) fclose(infile); - ConfigTemplate* pConfigTemplate = new ConfigTemplate(pScript, stringBuilder.GetBuffer()); - pConfigTemplates->push_back(pConfigTemplate); + ConfigTemplate* configTemplate = new ConfigTemplate(script, stringBuilder.GetBuffer()); + configTemplates->push_back(configTemplate); } // clearing the list without deleting of objects, which are in pConfigTemplates now @@ -356,7 +356,7 @@ bool ScriptConfig::LoadConfigTemplates(ConfigTemplates* pConfigTemplates) void ScriptConfig::InitConfigTemplates() { - if (!LoadConfigTemplates(&m_ConfigTemplates)) + if (!LoadConfigTemplates(&m_configTemplates)) { error("Could not read configuration templates"); } @@ -364,10 +364,10 @@ void ScriptConfig::InitConfigTemplates() void ScriptConfig::InitScripts() { - LoadScripts(&m_Scripts); + LoadScripts(&m_scripts); } -void ScriptConfig::LoadScripts(Scripts* pScripts) +void ScriptConfig::LoadScripts(Scripts* scripts) { if (strlen(g_pOptions->GetScriptDir()) == 0) { @@ -380,180 +380,180 @@ void ScriptConfig::LoadScripts(Scripts* pScripts) // first add all scripts from m_szScriptOrder Tokenizer tok(g_pOptions->GetScriptOrder(), ",;"); - while (const char* szScriptName = tok.Next()) + while (const char* scriptName = tok.Next()) { - Script* pScript = tmpScripts.Find(szScriptName); - if (pScript) + Script* script = tmpScripts.Find(scriptName); + if (script) { - tmpScripts.remove(pScript); - pScripts->push_back(pScript); + tmpScripts.remove(script); + scripts->push_back(script); } } // second add all other scripts from scripts directory for (Scripts::iterator it = tmpScripts.begin(); it != tmpScripts.end(); it++) { - Script* pScript = *it; - if (!pScripts->Find(pScript->GetName())) + Script* script = *it; + if (!scripts->Find(script->GetName())) { - pScripts->push_back(pScript); + scripts->push_back(script); } } tmpScripts.clear(); - BuildScriptDisplayNames(pScripts); + BuildScriptDisplayNames(scripts); } -void ScriptConfig::LoadScriptDir(Scripts* pScripts, const char* szDirectory, bool bIsSubDir) +void ScriptConfig::LoadScriptDir(Scripts* scripts, const char* directory, bool isSubDir) { - int iBufSize = 1024*10; - char* szBuffer = (char*)malloc(iBufSize+1); + int bufSize = 1024*10; + char* buffer = (char*)malloc(bufSize+1); - const int iBeginSignatureLen = strlen(BEGIN_SCRIPT_SIGNATURE); - const int iQueueEventsSignatureLen = strlen(QUEUE_EVENTS_SIGNATURE); + const int beginSignatureLen = strlen(BEGIN_SCRIPT_SIGNATURE); + const int queueEventsSignatureLen = strlen(QUEUE_EVENTS_SIGNATURE); - DirBrowser dir(szDirectory); - while (const char* szFilename = dir.Next()) + DirBrowser dir(directory); + while (const char* filename = dir.Next()) { - if (szFilename[0] != '.' && szFilename[0] != '_') + if (filename[0] != '.' && filename[0] != '_') { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%s", szDirectory, szFilename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%s", directory, filename); + fullFilename[1024-1] = '\0'; - if (!Util::DirectoryExists(szFullFilename)) + if (!Util::DirectoryExists(fullFilename)) { // check if the file contains pp-script-signature - FILE* infile = fopen(szFullFilename, FOPEN_RB); + FILE* infile = fopen(fullFilename, FOPEN_RB); if (infile) { // read first 10KB of the file and look for signature - int iReadBytes = fread(szBuffer, 1, iBufSize, infile); + int readBytes = fread(buffer, 1, bufSize, infile); fclose(infile); - szBuffer[iReadBytes] = 0; + buffer[readBytes] = 0; // split buffer into lines - Tokenizer tok(szBuffer, "\n\r", true); - while (char* szLine = tok.Next()) + Tokenizer tok(buffer, "\n\r", true); + while (char* line = tok.Next()) { - if (!strncmp(szLine, BEGIN_SCRIPT_SIGNATURE, iBeginSignatureLen) && - strstr(szLine, END_SCRIPT_SIGNATURE)) + if (!strncmp(line, BEGIN_SCRIPT_SIGNATURE, beginSignatureLen) && + strstr(line, END_SCRIPT_SIGNATURE)) { - bool bPostScript = strstr(szLine, POST_SCRIPT_SIGNATURE); - bool bScanScript = strstr(szLine, SCAN_SCRIPT_SIGNATURE); - bool bQueueScript = strstr(szLine, QUEUE_SCRIPT_SIGNATURE); - bool bSchedulerScript = strstr(szLine, SCHEDULER_SCRIPT_SIGNATURE); - bool bFeedScript = strstr(szLine, FEED_SCRIPT_SIGNATURE); - if (bPostScript || bScanScript || bQueueScript || bSchedulerScript || bFeedScript) + bool postScript = strstr(line, POST_SCRIPT_SIGNATURE); + bool scanScript = strstr(line, SCAN_SCRIPT_SIGNATURE); + bool queueScript = strstr(line, QUEUE_SCRIPT_SIGNATURE); + bool schedulerScript = strstr(line, SCHEDULER_SCRIPT_SIGNATURE); + bool feedScript = strstr(line, FEED_SCRIPT_SIGNATURE); + if (postScript || scanScript || queueScript || schedulerScript || feedScript) { - char szScriptName[1024]; - if (bIsSubDir) + char scriptName[1024]; + if (isSubDir) { - char szDirectory2[1024]; - snprintf(szDirectory2, 1024, "%s", szDirectory); - szDirectory2[1024-1] = '\0'; - int iLen = strlen(szDirectory2); - if (szDirectory2[iLen-1] == PATH_SEPARATOR || szDirectory2[iLen-1] == ALT_PATH_SEPARATOR) + char directory2[1024]; + snprintf(directory2, 1024, "%s", directory); + directory2[1024-1] = '\0'; + int len = strlen(directory2); + if (directory2[len-1] == PATH_SEPARATOR || directory2[len-1] == ALT_PATH_SEPARATOR) { // trim last path-separator - szDirectory2[iLen-1] = '\0'; + directory2[len-1] = '\0'; } - snprintf(szScriptName, 1024, "%s%c%s", Util::BaseFileName(szDirectory2), PATH_SEPARATOR, szFilename); + snprintf(scriptName, 1024, "%s%c%s", Util::BaseFileName(directory2), PATH_SEPARATOR, filename); } else { - snprintf(szScriptName, 1024, "%s", szFilename); + snprintf(scriptName, 1024, "%s", filename); } - szScriptName[1024-1] = '\0'; + scriptName[1024-1] = '\0'; - char* szQueueEvents = NULL; - if (bQueueScript) + char* queueEvents = NULL; + if (queueScript) { - while (char* szLine = tok.Next()) + while (char* line = tok.Next()) { - if (!strncmp(szLine, QUEUE_EVENTS_SIGNATURE, iQueueEventsSignatureLen)) + if (!strncmp(line, QUEUE_EVENTS_SIGNATURE, queueEventsSignatureLen)) { - szQueueEvents = szLine + iQueueEventsSignatureLen; + queueEvents = line + queueEventsSignatureLen; break; } } } - Script* pScript = new Script(szScriptName, szFullFilename); - pScript->SetPostScript(bPostScript); - pScript->SetScanScript(bScanScript); - pScript->SetQueueScript(bQueueScript); - pScript->SetSchedulerScript(bSchedulerScript); - pScript->SetFeedScript(bFeedScript); - pScript->SetQueueEvents(szQueueEvents); - pScripts->push_back(pScript); + Script* script = new Script(scriptName, fullFilename); + script->SetPostScript(postScript); + script->SetScanScript(scanScript); + script->SetQueueScript(queueScript); + script->SetSchedulerScript(schedulerScript); + script->SetFeedScript(feedScript); + script->SetQueueEvents(queueEvents); + scripts->push_back(script); break; } } } } } - else if (!bIsSubDir) + else if (!isSubDir) { - snprintf(szFullFilename, 1024, "%s%s%c", szDirectory, szFilename, PATH_SEPARATOR); - szFullFilename[1024-1] = '\0'; + snprintf(fullFilename, 1024, "%s%s%c", directory, filename, PATH_SEPARATOR); + fullFilename[1024-1] = '\0'; - LoadScriptDir(pScripts, szFullFilename, true); + LoadScriptDir(scripts, fullFilename, true); } } } - free(szBuffer); + free(buffer); } -bool ScriptConfig::CompareScripts(Script* pScript1, Script* pScript2) +bool ScriptConfig::CompareScripts(Script* script1, Script* script2) { - return strcmp(pScript1->GetName(), pScript2->GetName()) < 0; + return strcmp(script1->GetName(), script2->GetName()) < 0; } -void ScriptConfig::BuildScriptDisplayNames(Scripts* pScripts) +void ScriptConfig::BuildScriptDisplayNames(Scripts* scripts) { // trying to use short name without path and extension. // if there are other scripts with the same short name - using a longer name instead (with ot without extension) - for (Scripts::iterator it = pScripts->begin(); it != pScripts->end(); it++) + for (Scripts::iterator it = scripts->begin(); it != scripts->end(); it++) { - Script* pScript = *it; + Script* script = *it; - char szShortName[256]; - strncpy(szShortName, pScript->GetName(), 256); - szShortName[256-1] = '\0'; - if (char* ext = strrchr(szShortName, '.')) *ext = '\0'; // strip file extension + char shortName[256]; + strncpy(shortName, script->GetName(), 256); + shortName[256-1] = '\0'; + if (char* ext = strrchr(shortName, '.')) *ext = '\0'; // strip file extension - const char* szDisplayName = Util::BaseFileName(szShortName); + const char* displayName = Util::BaseFileName(shortName); - for (Scripts::iterator it2 = pScripts->begin(); it2 != pScripts->end(); it2++) + for (Scripts::iterator it2 = scripts->begin(); it2 != scripts->end(); it2++) { - Script* pScript2 = *it2; + Script* script2 = *it2; - char szShortName2[256]; - strncpy(szShortName2, pScript2->GetName(), 256); - szShortName2[256-1] = '\0'; - if (char* ext = strrchr(szShortName2, '.')) *ext = '\0'; // strip file extension + char shortName2[256]; + strncpy(shortName2, script2->GetName(), 256); + shortName2[256-1] = '\0'; + if (char* ext = strrchr(shortName2, '.')) *ext = '\0'; // strip file extension - const char* szDisplayName2 = Util::BaseFileName(szShortName2); + const char* displayName2 = Util::BaseFileName(shortName2); - if (!strcmp(szDisplayName, szDisplayName2) && pScript->GetName() != pScript2->GetName()) + if (!strcmp(displayName, displayName2) && script->GetName() != script2->GetName()) { - if (!strcmp(szShortName, szShortName2)) + if (!strcmp(shortName, shortName2)) { - szDisplayName = pScript->GetName(); + displayName = script->GetName(); } else { - szDisplayName = szShortName; + displayName = shortName; } break; } } - pScript->SetDisplayName(szDisplayName); + script->SetDisplayName(displayName); } } diff --git a/daemon/extension/ScriptConfig.h b/daemon/extension/ScriptConfig.h index 4451530c..56a18247 100644 --- a/daemon/extension/ScriptConfig.h +++ b/daemon/extension/ScriptConfig.h @@ -38,35 +38,35 @@ public: class Script { private: - char* m_szName; - char* m_szLocation; - char* m_szDisplayName; - bool m_bPostScript; - bool m_bScanScript; - bool m_bQueueScript; - bool m_bSchedulerScript; - bool m_bFeedScript; - char* m_szQueueEvents; + char* m_name; + char* m_location; + char* m_displayName; + bool m_postScript; + bool m_scanScript; + bool m_queueScript; + bool m_schedulerScript; + bool m_feedScript; + char* m_queueEvents; public: - Script(const char* szName, const char* szLocation); + Script(const char* name, const char* location); ~Script(); - const char* GetName() { return m_szName; } - const char* GetLocation() { return m_szLocation; } - void SetDisplayName(const char* szDisplayName); - const char* GetDisplayName() { return m_szDisplayName; } - bool GetPostScript() { return m_bPostScript; } - void SetPostScript(bool bPostScript) { m_bPostScript = bPostScript; } - bool GetScanScript() { return m_bScanScript; } - void SetScanScript(bool bScanScript) { m_bScanScript = bScanScript; } - bool GetQueueScript() { return m_bQueueScript; } - void SetQueueScript(bool bQueueScript) { m_bQueueScript = bQueueScript; } - bool GetSchedulerScript() { return m_bSchedulerScript; } - void SetSchedulerScript(bool bSchedulerScript) { m_bSchedulerScript = bSchedulerScript; } - bool GetFeedScript() { return m_bFeedScript; } - void SetFeedScript(bool bFeedScript) { m_bFeedScript = bFeedScript; } - void SetQueueEvents(const char* szQueueEvents); - const char* GetQueueEvents() { return m_szQueueEvents; } + const char* GetName() { return m_name; } + const char* GetLocation() { return m_location; } + void SetDisplayName(const char* displayName); + const char* GetDisplayName() { return m_displayName; } + bool GetPostScript() { return m_postScript; } + void SetPostScript(bool postScript) { m_postScript = postScript; } + bool GetScanScript() { return m_scanScript; } + void SetScanScript(bool scanScript) { m_scanScript = scanScript; } + bool GetQueueScript() { return m_queueScript; } + void SetQueueScript(bool queueScript) { m_queueScript = queueScript; } + bool GetSchedulerScript() { return m_schedulerScript; } + void SetSchedulerScript(bool schedulerScript) { m_schedulerScript = schedulerScript; } + bool GetFeedScript() { return m_feedScript; } + void SetFeedScript(bool feedScript) { m_feedScript = feedScript; } + void SetQueueEvents(const char* queueEvents); + const char* GetQueueEvents() { return m_queueEvents; } }; typedef std::list ScriptsBase; @@ -76,22 +76,22 @@ public: public: ~Scripts(); void Clear(); - Script* Find(const char* szName); + Script* Find(const char* name); }; class ConfigTemplate { private: - Script* m_pScript; - char* m_szTemplate; + Script* m_script; + char* m_template; friend class Options; public: - ConfigTemplate(Script* pScript, const char* szTemplate); + ConfigTemplate(Script* script, const char* templ); ~ConfigTemplate(); - Script* GetScript() { return m_pScript; } - const char* GetTemplate() { return m_szTemplate; } + Script* GetScript() { return m_script; } + const char* GetTemplate() { return m_template; } }; typedef std::vector ConfigTemplatesBase; @@ -103,24 +103,24 @@ public: }; private: - Scripts m_Scripts; - ConfigTemplates m_ConfigTemplates; + Scripts m_scripts; + ConfigTemplates m_configTemplates; void InitScripts(); void InitConfigTemplates(); - static bool CompareScripts(Script* pScript1, Script* pScript2); - void LoadScriptDir(Scripts* pScripts, const char* szDirectory, bool bIsSubDir); - void BuildScriptDisplayNames(Scripts* pScripts); - void LoadScripts(Scripts* pScripts); + static bool CompareScripts(Script* script1, Script* script2); + void LoadScriptDir(Scripts* scripts, const char* directory, bool isSubDir); + void BuildScriptDisplayNames(Scripts* scripts); + void LoadScripts(Scripts* scripts); public: ScriptConfig(); ~ScriptConfig(); - Scripts* GetScripts() { return &m_Scripts; } - bool LoadConfig(Options::OptEntries* pOptEntries); - bool SaveConfig(Options::OptEntries* pOptEntries); - bool LoadConfigTemplates(ConfigTemplates* pConfigTemplates); - ConfigTemplates* GetConfigTemplates() { return &m_ConfigTemplates; } + Scripts* GetScripts() { return &m_scripts; } + bool LoadConfig(Options::OptEntries* optEntries); + bool SaveConfig(Options::OptEntries* optEntries); + bool LoadConfigTemplates(ConfigTemplates* configTemplates); + ConfigTemplates* GetConfigTemplates() { return &m_configTemplates; } }; extern ScriptConfig* g_pScriptConfig; diff --git a/daemon/feed/FeedCoordinator.cpp b/daemon/feed/FeedCoordinator.cpp index 68414df6..3e66ee4a 100644 --- a/daemon/feed/FeedCoordinator.cpp +++ b/daemon/feed/FeedCoordinator.cpp @@ -51,71 +51,71 @@ #include "DiskState.h" #include "DupeCoordinator.h" -FeedCoordinator::FeedCacheItem::FeedCacheItem(const char* szUrl, int iCacheTimeSec,const char* szCacheId, - time_t tLastUsage, FeedItemInfos* pFeedItemInfos) +FeedCoordinator::FeedCacheItem::FeedCacheItem(const char* url, int cacheTimeSec,const char* cacheId, + time_t lastUsage, FeedItemInfos* feedItemInfos) { - m_szUrl = strdup(szUrl); - m_iCacheTimeSec = iCacheTimeSec; - m_szCacheId = strdup(szCacheId); - m_tLastUsage = tLastUsage; - m_pFeedItemInfos = pFeedItemInfos; - m_pFeedItemInfos->Retain(); + m_url = strdup(url); + m_cacheTimeSec = cacheTimeSec; + m_cacheId = strdup(cacheId); + m_lastUsage = lastUsage; + m_feedItemInfos = feedItemInfos; + m_feedItemInfos->Retain(); } FeedCoordinator::FeedCacheItem::~FeedCacheItem() { - free(m_szUrl); - free(m_szCacheId); - m_pFeedItemInfos->Release(); + free(m_url); + free(m_cacheId); + m_feedItemInfos->Release(); } FeedCoordinator::FilterHelper::FilterHelper() { - m_pSeasonEpisodeRegEx = NULL; + m_seasonEpisodeRegEx = NULL; } FeedCoordinator::FilterHelper::~FilterHelper() { - delete m_pSeasonEpisodeRegEx; + delete m_seasonEpisodeRegEx; } -void FeedCoordinator::FilterHelper::CalcDupeStatus(const char* szTitle, const char* szDupeKey, char* szStatusBuf, int iBufLen) +void FeedCoordinator::FilterHelper::CalcDupeStatus(const char* title, const char* dupeKey, char* statusBuf, int bufLen) { - const char* szDupeStatusName[] = { "", "QUEUED", "DOWNLOADING", "3", "SUCCESS", "5", "6", "7", "WARNING", + const char* dupeStatusName[] = { "", "QUEUED", "DOWNLOADING", "3", "SUCCESS", "5", "6", "7", "WARNING", "9", "10", "11", "12", "13", "14", "15", "FAILURE" }; - char szStatuses[200]; - szStatuses[0] = '\0'; + char statuses[200]; + statuses[0] = '\0'; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - DupeCoordinator::EDupeStatus eDupeStatus = g_pDupeCoordinator->GetDupeStatus(pDownloadQueue, szTitle, szDupeKey); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + DupeCoordinator::EDupeStatus dupeStatus = g_pDupeCoordinator->GetDupeStatus(downloadQueue, title, dupeKey); DownloadQueue::Unlock(); for (int i = 1; i <= (int)DupeCoordinator::dsFailure; i = i << 1) { - if (eDupeStatus & i) + if (dupeStatus & i) { - if (*szStatuses) + if (*statuses) { - strcat(szStatuses, ","); + strcat(statuses, ","); } - strcat(szStatuses, szDupeStatusName[i]); + strcat(statuses, dupeStatusName[i]); } } - strncpy(szStatusBuf, szStatuses, iBufLen); + strncpy(statusBuf, statuses, bufLen); } FeedCoordinator::FeedCoordinator() { debug("Creating FeedCoordinator"); - m_bForce = false; - m_bSave = false; + m_force = false; + m_save = false; g_pLog->RegisterDebuggable(this); - m_DownloadQueueObserver.m_pOwner = this; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - pDownloadQueue->Attach(&m_DownloadQueueObserver); + m_downloadQueueObserver.m_owner = this; + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + downloadQueue->Attach(&m_downloadQueueObserver); DownloadQueue::Unlock(); } @@ -127,32 +127,32 @@ FeedCoordinator::~FeedCoordinator() g_pLog->UnregisterDebuggable(this); debug("Deleting FeedDownloaders"); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { delete *it; } - m_ActiveDownloads.clear(); + m_activeDownloads.clear(); debug("Deleting Feeds"); - for (Feeds::iterator it = m_Feeds.begin(); it != m_Feeds.end(); it++) + for (Feeds::iterator it = m_feeds.begin(); it != m_feeds.end(); it++) { delete *it; } - m_Feeds.clear(); + m_feeds.clear(); debug("Deleting FeedCache"); - for (FeedCache::iterator it = m_FeedCache.begin(); it != m_FeedCache.end(); it++) + for (FeedCache::iterator it = m_feedCache.begin(); it != m_feedCache.end(); it++) { delete *it; } - m_FeedCache.clear(); + m_feedCache.clear(); debug("FeedCoordinator destroyed"); } -void FeedCoordinator::AddFeed(FeedInfo* pFeedInfo) +void FeedCoordinator::AddFeed(FeedInfo* feedInfo) { - m_Feeds.push_back(pFeedInfo); + m_feeds.push_back(feedInfo); } void FeedCoordinator::Run() @@ -166,65 +166,65 @@ void FeedCoordinator::Run() if (g_pOptions->GetServerMode() && g_pOptions->GetSaveQueue() && g_pOptions->GetReloadQueue()) { - m_mutexDownloads.Lock(); - g_pDiskState->LoadFeeds(&m_Feeds, &m_FeedHistory); - m_mutexDownloads.Unlock(); + m_downloadsMutex.Lock(); + g_pDiskState->LoadFeeds(&m_feeds, &m_feedHistory); + m_downloadsMutex.Unlock(); } - int iSleepInterval = 100; - int iUpdateCounter = 0; - int iCleanupCounter = 60000; + int sleepInterval = 100; + int updateCounter = 0; + int cleanupCounter = 60000; while (!IsStopped()) { - usleep(iSleepInterval * 1000); + usleep(sleepInterval * 1000); - iUpdateCounter += iSleepInterval; - if (iUpdateCounter >= 1000) + updateCounter += sleepInterval; + if (updateCounter >= 1000) { // this code should not be called too often, once per second is OK - if (!g_pOptions->GetPauseDownload() || m_bForce || g_pOptions->GetUrlForce()) + if (!g_pOptions->GetPauseDownload() || m_force || g_pOptions->GetUrlForce()) { - m_mutexDownloads.Lock(); - time_t tCurrent = time(NULL); - if ((int)m_ActiveDownloads.size() < g_pOptions->GetUrlConnections()) + m_downloadsMutex.Lock(); + time_t current = time(NULL); + if ((int)m_activeDownloads.size() < g_pOptions->GetUrlConnections()) { - m_bForce = false; + m_force = false; // check feed list and update feeds - for (Feeds::iterator it = m_Feeds.begin(); it != m_Feeds.end(); it++) + for (Feeds::iterator it = m_feeds.begin(); it != m_feeds.end(); it++) { - FeedInfo* pFeedInfo = *it; - if (((pFeedInfo->GetInterval() > 0 && - (tCurrent - pFeedInfo->GetLastUpdate() >= pFeedInfo->GetInterval() * 60 || - tCurrent < pFeedInfo->GetLastUpdate())) || - pFeedInfo->GetFetch()) && - pFeedInfo->GetStatus() != FeedInfo::fsRunning) + FeedInfo* feedInfo = *it; + if (((feedInfo->GetInterval() > 0 && + (current - feedInfo->GetLastUpdate() >= feedInfo->GetInterval() * 60 || + current < feedInfo->GetLastUpdate())) || + feedInfo->GetFetch()) && + feedInfo->GetStatus() != FeedInfo::fsRunning) { - StartFeedDownload(pFeedInfo, pFeedInfo->GetFetch()); + StartFeedDownload(feedInfo, feedInfo->GetFetch()); } - else if (pFeedInfo->GetFetch()) + else if (feedInfo->GetFetch()) { - m_bForce = true; + m_force = true; } } } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } CheckSaveFeeds(); ResetHangingDownloads(); - iUpdateCounter = 0; + updateCounter = 0; } - iCleanupCounter += iSleepInterval; - if (iCleanupCounter >= 60000) + cleanupCounter += sleepInterval; + if (cleanupCounter >= 60000) { // clean up feed history once a minute CleanupHistory(); CleanupCache(); CheckSaveFeeds(); - iCleanupCounter = 0; + cleanupCounter = 0; } } @@ -233,9 +233,9 @@ void FeedCoordinator::Run() bool completed = false; while (!completed) { - m_mutexDownloads.Lock(); - completed = m_ActiveDownloads.size() == 0; - m_mutexDownloads.Unlock(); + m_downloadsMutex.Lock(); + completed = m_activeDownloads.size() == 0; + m_downloadsMutex.Unlock(); CheckSaveFeeds(); usleep(100 * 1000); ResetHangingDownloads(); @@ -250,12 +250,12 @@ void FeedCoordinator::Stop() Thread::Stop(); debug("Stopping UrlDownloads"); - m_mutexDownloads.Lock(); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + m_downloadsMutex.Lock(); + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { (*it)->Stop(); } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); debug("UrlDownloads are notified"); } @@ -267,77 +267,77 @@ void FeedCoordinator::ResetHangingDownloads() return; } - m_mutexDownloads.Lock(); + m_downloadsMutex.Lock(); time_t tm = ::time(NULL); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end();) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end();) { - FeedDownloader* pFeedDownloader = *it; - if (tm - pFeedDownloader->GetLastUpdateTime() > TimeOut && - pFeedDownloader->GetStatus() == FeedDownloader::adRunning) + FeedDownloader* feedDownloader = *it; + if (tm - feedDownloader->GetLastUpdateTime() > TimeOut && + feedDownloader->GetStatus() == FeedDownloader::adRunning) { - debug("Terminating hanging download %s", pFeedDownloader->GetInfoName()); - if (pFeedDownloader->Terminate()) + debug("Terminating hanging download %s", feedDownloader->GetInfoName()); + if (feedDownloader->Terminate()) { - error("Terminated hanging download %s", pFeedDownloader->GetInfoName()); - pFeedDownloader->GetFeedInfo()->SetStatus(FeedInfo::fsUndefined); + error("Terminated hanging download %s", feedDownloader->GetInfoName()); + feedDownloader->GetFeedInfo()->SetStatus(FeedInfo::fsUndefined); } else { - error("Could not terminate hanging download %s", pFeedDownloader->GetInfoName()); + error("Could not terminate hanging download %s", feedDownloader->GetInfoName()); } - m_ActiveDownloads.erase(it); + m_activeDownloads.erase(it); // it's not safe to destroy pFeedDownloader, because the state of object is unknown - delete pFeedDownloader; - it = m_ActiveDownloads.begin(); + delete feedDownloader; + it = m_activeDownloads.begin(); continue; } it++; } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } void FeedCoordinator::LogDebugInfo() { info(" ---------- FeedCoordinator"); - m_mutexDownloads.Lock(); - info(" Active Downloads: %i", m_ActiveDownloads.size()); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + m_downloadsMutex.Lock(); + info(" Active Downloads: %i", m_activeDownloads.size()); + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { - FeedDownloader* pFeedDownloader = *it; - pFeedDownloader->LogDebugInfo(); + FeedDownloader* feedDownloader = *it; + feedDownloader->LogDebugInfo(); } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } -void FeedCoordinator::StartFeedDownload(FeedInfo* pFeedInfo, bool bForce) +void FeedCoordinator::StartFeedDownload(FeedInfo* feedInfo, bool force) { - debug("Starting new FeedDownloader for %s", pFeedInfo->GetName()); + debug("Starting new FeedDownloader for %s", feedInfo->GetName()); - FeedDownloader* pFeedDownloader = new FeedDownloader(); - pFeedDownloader->SetAutoDestroy(true); - pFeedDownloader->Attach(this); - pFeedDownloader->SetFeedInfo(pFeedInfo); - pFeedDownloader->SetURL(pFeedInfo->GetUrl()); - if (strlen(pFeedInfo->GetName()) > 0) + FeedDownloader* feedDownloader = new FeedDownloader(); + feedDownloader->SetAutoDestroy(true); + feedDownloader->Attach(this); + feedDownloader->SetFeedInfo(feedInfo); + feedDownloader->SetURL(feedInfo->GetUrl()); + if (strlen(feedInfo->GetName()) > 0) { - pFeedDownloader->SetInfoName(pFeedInfo->GetName()); + feedDownloader->SetInfoName(feedInfo->GetName()); } else { - char szUrlName[1024]; - NZBInfo::MakeNiceUrlName(pFeedInfo->GetUrl(), "", szUrlName, sizeof(szUrlName)); - pFeedDownloader->SetInfoName(szUrlName); + char urlName[1024]; + NZBInfo::MakeNiceUrlName(feedInfo->GetUrl(), "", urlName, sizeof(urlName)); + feedDownloader->SetInfoName(urlName); } - pFeedDownloader->SetForce(bForce || g_pOptions->GetUrlForce()); + feedDownloader->SetForce(force || g_pOptions->GetUrlForce()); char tmp[1024]; - if (pFeedInfo->GetID() > 0) + if (feedInfo->GetID() > 0) { - snprintf(tmp, 1024, "%sfeed-%i.tmp", g_pOptions->GetTempDir(), pFeedInfo->GetID()); + snprintf(tmp, 1024, "%sfeed-%i.tmp", g_pOptions->GetTempDir(), feedInfo->GetID()); } else { @@ -345,422 +345,422 @@ void FeedCoordinator::StartFeedDownload(FeedInfo* pFeedInfo, bool bForce) } tmp[1024-1] = '\0'; - pFeedDownloader->SetOutputFilename(tmp); + feedDownloader->SetOutputFilename(tmp); - pFeedInfo->SetStatus(FeedInfo::fsRunning); - pFeedInfo->SetForce(bForce); - pFeedInfo->SetFetch(false); + feedInfo->SetStatus(FeedInfo::fsRunning); + feedInfo->SetForce(force); + feedInfo->SetFetch(false); - m_ActiveDownloads.push_back(pFeedDownloader); - pFeedDownloader->Start(); + m_activeDownloads.push_back(feedDownloader); + feedDownloader->Start(); } -void FeedCoordinator::Update(Subject* pCaller, void* pAspect) +void FeedCoordinator::Update(Subject* caller, void* aspect) { debug("Notification from FeedDownloader received"); - FeedDownloader* pFeedDownloader = (FeedDownloader*) pCaller; - if ((pFeedDownloader->GetStatus() == WebDownloader::adFinished) || - (pFeedDownloader->GetStatus() == WebDownloader::adFailed) || - (pFeedDownloader->GetStatus() == WebDownloader::adRetry)) + FeedDownloader* feedDownloader = (FeedDownloader*) caller; + if ((feedDownloader->GetStatus() == WebDownloader::adFinished) || + (feedDownloader->GetStatus() == WebDownloader::adFailed) || + (feedDownloader->GetStatus() == WebDownloader::adRetry)) { - FeedCompleted(pFeedDownloader); + FeedCompleted(feedDownloader); } } -void FeedCoordinator::FeedCompleted(FeedDownloader* pFeedDownloader) +void FeedCoordinator::FeedCompleted(FeedDownloader* feedDownloader) { debug("Feed downloaded"); - FeedInfo* pFeedInfo = pFeedDownloader->GetFeedInfo(); - bool bStatusOK = pFeedDownloader->GetStatus() == WebDownloader::adFinished; - if (bStatusOK) + FeedInfo* feedInfo = feedDownloader->GetFeedInfo(); + bool statusOK = feedDownloader->GetStatus() == WebDownloader::adFinished; + if (statusOK) { - pFeedInfo->SetOutputFilename(pFeedDownloader->GetOutputFilename()); + feedInfo->SetOutputFilename(feedDownloader->GetOutputFilename()); } // delete Download from Queue - m_mutexDownloads.Lock(); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + m_downloadsMutex.Lock(); + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { FeedDownloader* pa = *it; - if (pa == pFeedDownloader) + if (pa == feedDownloader) { - m_ActiveDownloads.erase(it); + m_activeDownloads.erase(it); break; } } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); - if (bStatusOK) + if (statusOK) { - if (!pFeedInfo->GetPreview()) + if (!feedInfo->GetPreview()) { FeedScriptController::ExecuteScripts( - !Util::EmptyStr(pFeedInfo->GetFeedScript()) ? pFeedInfo->GetFeedScript(): g_pOptions->GetFeedScript(), - pFeedInfo->GetOutputFilename(), pFeedInfo->GetID()); - FeedFile* pFeedFile = FeedFile::Create(pFeedInfo->GetOutputFilename()); - remove(pFeedInfo->GetOutputFilename()); + !Util::EmptyStr(feedInfo->GetFeedScript()) ? feedInfo->GetFeedScript(): g_pOptions->GetFeedScript(), + feedInfo->GetOutputFilename(), feedInfo->GetID()); + FeedFile* feedFile = FeedFile::Create(feedInfo->GetOutputFilename()); + remove(feedInfo->GetOutputFilename()); NZBList addedNZBs; - m_mutexDownloads.Lock(); - if (pFeedFile) + m_downloadsMutex.Lock(); + if (feedFile) { - ProcessFeed(pFeedInfo, pFeedFile->GetFeedItemInfos(), &addedNZBs); - delete pFeedFile; + ProcessFeed(feedInfo, feedFile->GetFeedItemInfos(), &addedNZBs); + delete feedFile; } - pFeedInfo->SetLastUpdate(time(NULL)); - pFeedInfo->SetForce(false); - m_bSave = true; - m_mutexDownloads.Unlock(); + feedInfo->SetLastUpdate(time(NULL)); + feedInfo->SetForce(false); + m_save = true; + m_downloadsMutex.Unlock(); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); for (NZBList::iterator it = addedNZBs.begin(); it != addedNZBs.end(); it++) { - NZBInfo* pNZBInfo = *it; - pDownloadQueue->GetQueue()->Add(pNZBInfo, false); + NZBInfo* nzbInfo = *it; + downloadQueue->GetQueue()->Add(nzbInfo, false); } - pDownloadQueue->Save(); + downloadQueue->Save(); DownloadQueue::Unlock(); } - pFeedInfo->SetStatus(FeedInfo::fsFinished); + feedInfo->SetStatus(FeedInfo::fsFinished); } else { - pFeedInfo->SetStatus(FeedInfo::fsFailed); + feedInfo->SetStatus(FeedInfo::fsFailed); } } -void FeedCoordinator::FilterFeed(FeedInfo* pFeedInfo, FeedItemInfos* pFeedItemInfos) +void FeedCoordinator::FilterFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInfos) { - debug("Filtering feed %s", pFeedInfo->GetName()); + debug("Filtering feed %s", feedInfo->GetName()); - FeedFilter* pFeedFilter = NULL; - if (pFeedInfo->GetFilter() && strlen(pFeedInfo->GetFilter()) > 0) + FeedFilter* feedFilter = NULL; + if (feedInfo->GetFilter() && strlen(feedInfo->GetFilter()) > 0) { - pFeedFilter = new FeedFilter(pFeedInfo->GetFilter()); + feedFilter = new FeedFilter(feedInfo->GetFilter()); } - for (FeedItemInfos::iterator it = pFeedItemInfos->begin(); it != pFeedItemInfos->end(); it++) + for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) { - FeedItemInfo* pFeedItemInfo = *it; - pFeedItemInfo->SetMatchStatus(FeedItemInfo::msAccepted); - pFeedItemInfo->SetMatchRule(0); - pFeedItemInfo->SetPauseNzb(pFeedInfo->GetPauseNzb()); - pFeedItemInfo->SetPriority(pFeedInfo->GetPriority()); - pFeedItemInfo->SetAddCategory(pFeedInfo->GetCategory()); - pFeedItemInfo->SetDupeScore(0); - pFeedItemInfo->SetDupeMode(dmScore); - pFeedItemInfo->SetFeedFilterHelper(&m_FilterHelper); - pFeedItemInfo->BuildDupeKey(NULL, NULL); - if (pFeedFilter) + FeedItemInfo* feedItemInfo = *it; + feedItemInfo->SetMatchStatus(FeedItemInfo::msAccepted); + feedItemInfo->SetMatchRule(0); + feedItemInfo->SetPauseNzb(feedInfo->GetPauseNzb()); + feedItemInfo->SetPriority(feedInfo->GetPriority()); + feedItemInfo->SetAddCategory(feedInfo->GetCategory()); + feedItemInfo->SetDupeScore(0); + feedItemInfo->SetDupeMode(dmScore); + feedItemInfo->SetFeedFilterHelper(&m_filterHelper); + feedItemInfo->BuildDupeKey(NULL, NULL); + if (feedFilter) { - pFeedFilter->Match(pFeedItemInfo); + feedFilter->Match(feedItemInfo); } } - delete pFeedFilter; + delete feedFilter; } -void FeedCoordinator::ProcessFeed(FeedInfo* pFeedInfo, FeedItemInfos* pFeedItemInfos, NZBList* pAddedNZBs) +void FeedCoordinator::ProcessFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInfos, NZBList* addedNzbs) { - debug("Process feed %s", pFeedInfo->GetName()); + debug("Process feed %s", feedInfo->GetName()); - FilterFeed(pFeedInfo, pFeedItemInfos); + FilterFeed(feedInfo, feedItemInfos); - bool bFirstFetch = pFeedInfo->GetLastUpdate() == 0; - int iAdded = 0; + bool firstFetch = feedInfo->GetLastUpdate() == 0; + int added = 0; - for (FeedItemInfos::iterator it = pFeedItemInfos->begin(); it != pFeedItemInfos->end(); it++) + for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) { - FeedItemInfo* pFeedItemInfo = *it; - if (pFeedItemInfo->GetMatchStatus() == FeedItemInfo::msAccepted) + FeedItemInfo* feedItemInfo = *it; + if (feedItemInfo->GetMatchStatus() == FeedItemInfo::msAccepted) { - FeedHistoryInfo* pFeedHistoryInfo = m_FeedHistory.Find(pFeedItemInfo->GetUrl()); - FeedHistoryInfo::EStatus eStatus = FeedHistoryInfo::hsUnknown; - if (bFirstFetch && pFeedInfo->GetBacklog()) + FeedHistoryInfo* feedHistoryInfo = m_feedHistory.Find(feedItemInfo->GetUrl()); + FeedHistoryInfo::EStatus status = FeedHistoryInfo::hsUnknown; + if (firstFetch && feedInfo->GetBacklog()) { - eStatus = FeedHistoryInfo::hsBacklog; + status = FeedHistoryInfo::hsBacklog; } - else if (!pFeedHistoryInfo) + else if (!feedHistoryInfo) { - NZBInfo* pNZBInfo = CreateNZBInfo(pFeedInfo, pFeedItemInfo); - pAddedNZBs->Add(pNZBInfo, false); - eStatus = FeedHistoryInfo::hsFetched; - iAdded++; + NZBInfo* nzbInfo = CreateNZBInfo(feedInfo, feedItemInfo); + addedNzbs->Add(nzbInfo, false); + status = FeedHistoryInfo::hsFetched; + added++; } - if (pFeedHistoryInfo) + if (feedHistoryInfo) { - pFeedHistoryInfo->SetLastSeen(time(NULL)); + feedHistoryInfo->SetLastSeen(time(NULL)); } else { - m_FeedHistory.Add(pFeedItemInfo->GetUrl(), eStatus, time(NULL)); + m_feedHistory.Add(feedItemInfo->GetUrl(), status, time(NULL)); } } } - if (iAdded) + if (added) { - info("%s has %i new item(s)", pFeedInfo->GetName(), iAdded); + info("%s has %i new item(s)", feedInfo->GetName(), added); } else { - detail("%s has no new items", pFeedInfo->GetName()); + detail("%s has no new items", feedInfo->GetName()); } } -NZBInfo* FeedCoordinator::CreateNZBInfo(FeedInfo* pFeedInfo, FeedItemInfo* pFeedItemInfo) +NZBInfo* FeedCoordinator::CreateNZBInfo(FeedInfo* feedInfo, FeedItemInfo* feedItemInfo) { - debug("Download %s from %s", pFeedItemInfo->GetUrl(), pFeedInfo->GetName()); + debug("Download %s from %s", feedItemInfo->GetUrl(), feedInfo->GetName()); - NZBInfo* pNZBInfo = new NZBInfo(); - pNZBInfo->SetKind(NZBInfo::nkUrl); - pNZBInfo->SetFeedID(pFeedInfo->GetID()); - pNZBInfo->SetURL(pFeedItemInfo->GetUrl()); + NZBInfo* nzbInfo = new NZBInfo(); + nzbInfo->SetKind(NZBInfo::nkUrl); + nzbInfo->SetFeedID(feedInfo->GetID()); + nzbInfo->SetURL(feedItemInfo->GetUrl()); // add .nzb-extension if not present - char szNZBName[1024]; - strncpy(szNZBName, pFeedItemInfo->GetFilename(), 1024); - szNZBName[1024-1] = '\0'; - char* ext = strrchr(szNZBName, '.'); + char nzbName[1024]; + strncpy(nzbName, feedItemInfo->GetFilename(), 1024); + nzbName[1024-1] = '\0'; + char* ext = strrchr(nzbName, '.'); if (ext && !strcasecmp(ext, ".nzb")) { *ext = '\0'; } - char szNZBName2[1024]; - snprintf(szNZBName2, 1024, "%s.nzb", szNZBName); - Util::MakeValidFilename(szNZBName2, '_', false); - if (strlen(szNZBName) > 0) + char nzbName2[1024]; + snprintf(nzbName2, 1024, "%s.nzb", nzbName); + Util::MakeValidFilename(nzbName2, '_', false); + if (strlen(nzbName) > 0) { - pNZBInfo->SetFilename(szNZBName2); + nzbInfo->SetFilename(nzbName2); } - pNZBInfo->SetCategory(pFeedItemInfo->GetAddCategory()); - pNZBInfo->SetPriority(pFeedItemInfo->GetPriority()); - pNZBInfo->SetAddUrlPaused(pFeedItemInfo->GetPauseNzb()); - pNZBInfo->SetDupeKey(pFeedItemInfo->GetDupeKey()); - pNZBInfo->SetDupeScore(pFeedItemInfo->GetDupeScore()); - pNZBInfo->SetDupeMode(pFeedItemInfo->GetDupeMode()); + nzbInfo->SetCategory(feedItemInfo->GetAddCategory()); + nzbInfo->SetPriority(feedItemInfo->GetPriority()); + nzbInfo->SetAddUrlPaused(feedItemInfo->GetPauseNzb()); + nzbInfo->SetDupeKey(feedItemInfo->GetDupeKey()); + nzbInfo->SetDupeScore(feedItemInfo->GetDupeScore()); + nzbInfo->SetDupeMode(feedItemInfo->GetDupeMode()); - return pNZBInfo; + return nzbInfo; } -bool FeedCoordinator::ViewFeed(int iID, FeedItemInfos** ppFeedItemInfos) +bool FeedCoordinator::ViewFeed(int id, FeedItemInfos** ppFeedItemInfos) { - if (iID < 1 || iID > (int)m_Feeds.size()) + if (id < 1 || id > (int)m_feeds.size()) { return false; } - FeedInfo* pFeedInfo = m_Feeds.at(iID - 1); + FeedInfo* feedInfo = m_feeds.at(id - 1); - return PreviewFeed(pFeedInfo->GetID(), pFeedInfo->GetName(), pFeedInfo->GetUrl(), pFeedInfo->GetFilter(), - pFeedInfo->GetBacklog(), pFeedInfo->GetPauseNzb(), pFeedInfo->GetCategory(), - pFeedInfo->GetPriority(), pFeedInfo->GetInterval(), pFeedInfo->GetFeedScript(), 0, NULL, ppFeedItemInfos); + return PreviewFeed(feedInfo->GetID(), feedInfo->GetName(), feedInfo->GetUrl(), feedInfo->GetFilter(), + feedInfo->GetBacklog(), feedInfo->GetPauseNzb(), feedInfo->GetCategory(), + feedInfo->GetPriority(), feedInfo->GetInterval(), feedInfo->GetFeedScript(), 0, NULL, ppFeedItemInfos); } -bool FeedCoordinator::PreviewFeed(int iID, const char* szName, const char* szUrl, const char* szFilter, - bool bBacklog, bool bPauseNzb, const char* szCategory, int iPriority, int iInterval, const char* szFeedScript, - int iCacheTimeSec, const char* szCacheId, FeedItemInfos** ppFeedItemInfos) +bool FeedCoordinator::PreviewFeed(int id, const char* name, const char* url, const char* filter, + bool backlog, bool pauseNzb, const char* category, int priority, int interval, const char* feedScript, + int cacheTimeSec, const char* cacheId, FeedItemInfos** ppFeedItemInfos) { - debug("Preview feed %s", szName); + debug("Preview feed %s", name); - FeedInfo* pFeedInfo = new FeedInfo(iID, szName, szUrl, bBacklog, iInterval, - szFilter, bPauseNzb, szCategory, iPriority, szFeedScript); - pFeedInfo->SetPreview(true); + FeedInfo* feedInfo = new FeedInfo(id, name, url, backlog, interval, + filter, pauseNzb, category, priority, feedScript); + feedInfo->SetPreview(true); - FeedItemInfos* pFeedItemInfos = NULL; - bool bHasCache = false; - if (iCacheTimeSec > 0 && *szCacheId != '\0') + FeedItemInfos* feedItemInfos = NULL; + bool hasCache = false; + if (cacheTimeSec > 0 && *cacheId != '\0') { - m_mutexDownloads.Lock(); - for (FeedCache::iterator it = m_FeedCache.begin(); it != m_FeedCache.end(); it++) + m_downloadsMutex.Lock(); + for (FeedCache::iterator it = m_feedCache.begin(); it != m_feedCache.end(); it++) { - FeedCacheItem* pFeedCacheItem = *it; - if (!strcmp(pFeedCacheItem->GetCacheId(), szCacheId)) + FeedCacheItem* feedCacheItem = *it; + if (!strcmp(feedCacheItem->GetCacheId(), cacheId)) { - pFeedCacheItem->SetLastUsage(time(NULL)); - pFeedItemInfos = pFeedCacheItem->GetFeedItemInfos(); - pFeedItemInfos->Retain(); - bHasCache = true; + feedCacheItem->SetLastUsage(time(NULL)); + feedItemInfos = feedCacheItem->GetFeedItemInfos(); + feedItemInfos->Retain(); + hasCache = true; break; } } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } - if (!bHasCache) + if (!hasCache) { - m_mutexDownloads.Lock(); + m_downloadsMutex.Lock(); - bool bFirstFetch = true; - for (Feeds::iterator it = m_Feeds.begin(); it != m_Feeds.end(); it++) + bool firstFetch = true; + for (Feeds::iterator it = m_feeds.begin(); it != m_feeds.end(); it++) { - FeedInfo* pFeedInfo2 = *it; - if (!strcmp(pFeedInfo2->GetUrl(), pFeedInfo->GetUrl()) && - !strcmp(pFeedInfo2->GetFilter(), pFeedInfo->GetFilter()) && - pFeedInfo2->GetLastUpdate() > 0) + FeedInfo* feedInfo2 = *it; + if (!strcmp(feedInfo2->GetUrl(), feedInfo->GetUrl()) && + !strcmp(feedInfo2->GetFilter(), feedInfo->GetFilter()) && + feedInfo2->GetLastUpdate() > 0) { - bFirstFetch = false; + firstFetch = false; break; } } - StartFeedDownload(pFeedInfo, true); - m_mutexDownloads.Unlock(); + StartFeedDownload(feedInfo, true); + m_downloadsMutex.Unlock(); // wait until the download in a separate thread completes - while (pFeedInfo->GetStatus() == FeedInfo::fsRunning) + while (feedInfo->GetStatus() == FeedInfo::fsRunning) { usleep(100 * 1000); } // now can process the feed - FeedFile* pFeedFile = NULL; + FeedFile* feedFile = NULL; - if (pFeedInfo->GetStatus() == FeedInfo::fsFinished) + if (feedInfo->GetStatus() == FeedInfo::fsFinished) { FeedScriptController::ExecuteScripts( - !Util::EmptyStr(pFeedInfo->GetFeedScript()) ? pFeedInfo->GetFeedScript(): g_pOptions->GetFeedScript(), - pFeedInfo->GetOutputFilename(), pFeedInfo->GetID()); - pFeedFile = FeedFile::Create(pFeedInfo->GetOutputFilename()); + !Util::EmptyStr(feedInfo->GetFeedScript()) ? feedInfo->GetFeedScript(): g_pOptions->GetFeedScript(), + feedInfo->GetOutputFilename(), feedInfo->GetID()); + feedFile = FeedFile::Create(feedInfo->GetOutputFilename()); } - remove(pFeedInfo->GetOutputFilename()); + remove(feedInfo->GetOutputFilename()); - if (!pFeedFile) + if (!feedFile) { - delete pFeedInfo; + delete feedInfo; return false; } - pFeedItemInfos = pFeedFile->GetFeedItemInfos(); - pFeedItemInfos->Retain(); - delete pFeedFile; + feedItemInfos = feedFile->GetFeedItemInfos(); + feedItemInfos->Retain(); + delete feedFile; - for (FeedItemInfos::iterator it = pFeedItemInfos->begin(); it != pFeedItemInfos->end(); it++) + for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) { - FeedItemInfo* pFeedItemInfo = *it; - pFeedItemInfo->SetStatus(bFirstFetch && pFeedInfo->GetBacklog() ? FeedItemInfo::isBacklog : FeedItemInfo::isNew); - FeedHistoryInfo* pFeedHistoryInfo = m_FeedHistory.Find(pFeedItemInfo->GetUrl()); - if (pFeedHistoryInfo) + FeedItemInfo* feedItemInfo = *it; + feedItemInfo->SetStatus(firstFetch && feedInfo->GetBacklog() ? FeedItemInfo::isBacklog : FeedItemInfo::isNew); + FeedHistoryInfo* feedHistoryInfo = m_feedHistory.Find(feedItemInfo->GetUrl()); + if (feedHistoryInfo) { - pFeedItemInfo->SetStatus((FeedItemInfo::EStatus)pFeedHistoryInfo->GetStatus()); + feedItemInfo->SetStatus((FeedItemInfo::EStatus)feedHistoryInfo->GetStatus()); } } } - FilterFeed(pFeedInfo, pFeedItemInfos); - delete pFeedInfo; + FilterFeed(feedInfo, feedItemInfos); + delete feedInfo; - if (iCacheTimeSec > 0 && *szCacheId != '\0' && !bHasCache) + if (cacheTimeSec > 0 && *cacheId != '\0' && !hasCache) { - FeedCacheItem* pFeedCacheItem = new FeedCacheItem(szUrl, iCacheTimeSec, szCacheId, time(NULL), pFeedItemInfos); - m_mutexDownloads.Lock(); - m_FeedCache.push_back(pFeedCacheItem); - m_mutexDownloads.Unlock(); + FeedCacheItem* feedCacheItem = new FeedCacheItem(url, cacheTimeSec, cacheId, time(NULL), feedItemInfos); + m_downloadsMutex.Lock(); + m_feedCache.push_back(feedCacheItem); + m_downloadsMutex.Unlock(); } - *ppFeedItemInfos = pFeedItemInfos; + *ppFeedItemInfos = feedItemInfos; return true; } -void FeedCoordinator::FetchFeed(int iID) +void FeedCoordinator::FetchFeed(int id) { debug("FetchFeeds"); - m_mutexDownloads.Lock(); - for (Feeds::iterator it = m_Feeds.begin(); it != m_Feeds.end(); it++) + m_downloadsMutex.Lock(); + for (Feeds::iterator it = m_feeds.begin(); it != m_feeds.end(); it++) { - FeedInfo* pFeedInfo = *it; - if (pFeedInfo->GetID() == iID || iID == 0) + FeedInfo* feedInfo = *it; + if (feedInfo->GetID() == id || id == 0) { - pFeedInfo->SetFetch(true); - m_bForce = true; + feedInfo->SetFetch(true); + m_force = true; } } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } -void FeedCoordinator::DownloadQueueUpdate(Subject* pCaller, void* pAspect) +void FeedCoordinator::DownloadQueueUpdate(Subject* caller, void* aspect) { debug("Notification from URL-Coordinator received"); - DownloadQueue::Aspect* pQueueAspect = (DownloadQueue::Aspect*)pAspect; - if (pQueueAspect->eAction == DownloadQueue::eaUrlCompleted) + DownloadQueue::Aspect* queueAspect = (DownloadQueue::Aspect*)aspect; + if (queueAspect->action == DownloadQueue::eaUrlCompleted) { - m_mutexDownloads.Lock(); - FeedHistoryInfo* pFeedHistoryInfo = m_FeedHistory.Find(pQueueAspect->pNZBInfo->GetURL()); - if (pFeedHistoryInfo) + m_downloadsMutex.Lock(); + FeedHistoryInfo* feedHistoryInfo = m_feedHistory.Find(queueAspect->nzbInfo->GetURL()); + if (feedHistoryInfo) { - pFeedHistoryInfo->SetStatus(FeedHistoryInfo::hsFetched); + feedHistoryInfo->SetStatus(FeedHistoryInfo::hsFetched); } else { - m_FeedHistory.Add(pQueueAspect->pNZBInfo->GetURL(), FeedHistoryInfo::hsFetched, time(NULL)); + m_feedHistory.Add(queueAspect->nzbInfo->GetURL(), FeedHistoryInfo::hsFetched, time(NULL)); } - m_bSave = true; - m_mutexDownloads.Unlock(); + m_save = true; + m_downloadsMutex.Unlock(); } } bool FeedCoordinator::HasActiveDownloads() { - m_mutexDownloads.Lock(); - bool bActive = !m_ActiveDownloads.empty(); - m_mutexDownloads.Unlock(); - return bActive; + m_downloadsMutex.Lock(); + bool active = !m_activeDownloads.empty(); + m_downloadsMutex.Unlock(); + return active; } void FeedCoordinator::CheckSaveFeeds() { debug("CheckSaveFeeds"); - m_mutexDownloads.Lock(); - if (m_bSave) + m_downloadsMutex.Lock(); + if (m_save) { if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) { - g_pDiskState->SaveFeeds(&m_Feeds, &m_FeedHistory); + g_pDiskState->SaveFeeds(&m_feeds, &m_feedHistory); } - m_bSave = false; + m_save = false; } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } void FeedCoordinator::CleanupHistory() { debug("CleanupHistory"); - m_mutexDownloads.Lock(); + m_downloadsMutex.Lock(); - time_t tOldestUpdate = time(NULL); + time_t oldestUpdate = time(NULL); - for (Feeds::iterator it = m_Feeds.begin(); it != m_Feeds.end(); it++) + for (Feeds::iterator it = m_feeds.begin(); it != m_feeds.end(); it++) { - FeedInfo* pFeedInfo = *it; - if (pFeedInfo->GetLastUpdate() < tOldestUpdate) + FeedInfo* feedInfo = *it; + if (feedInfo->GetLastUpdate() < oldestUpdate) { - tOldestUpdate = pFeedInfo->GetLastUpdate(); + oldestUpdate = feedInfo->GetLastUpdate(); } } - time_t tBorderDate = tOldestUpdate - g_pOptions->GetFeedHistory() * 60*60*24; + time_t borderDate = oldestUpdate - g_pOptions->GetFeedHistory() * 60*60*24; int i = 0; - for (FeedHistory::iterator it = m_FeedHistory.begin(); it != m_FeedHistory.end(); ) + for (FeedHistory::iterator it = m_feedHistory.begin(); it != m_feedHistory.end(); ) { - FeedHistoryInfo* pFeedHistoryInfo = *it; - if (pFeedHistoryInfo->GetLastSeen() < tBorderDate) + FeedHistoryInfo* feedHistoryInfo = *it; + if (feedHistoryInfo->GetLastSeen() < borderDate) { - detail("Deleting %s from feed history", pFeedHistoryInfo->GetUrl()); - delete pFeedHistoryInfo; - m_FeedHistory.erase(it); - it = m_FeedHistory.begin() + i; - m_bSave = true; + detail("Deleting %s from feed history", feedHistoryInfo->GetUrl()); + delete feedHistoryInfo; + m_feedHistory.erase(it); + it = m_feedHistory.begin() + i; + m_save = true; } else { @@ -769,27 +769,27 @@ void FeedCoordinator::CleanupHistory() } } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } void FeedCoordinator::CleanupCache() { debug("CleanupCache"); - m_mutexDownloads.Lock(); + m_downloadsMutex.Lock(); - time_t tCurTime = time(NULL); + time_t curTime = time(NULL); int i = 0; - for (FeedCache::iterator it = m_FeedCache.begin(); it != m_FeedCache.end(); ) + for (FeedCache::iterator it = m_feedCache.begin(); it != m_feedCache.end(); ) { - FeedCacheItem* pFeedCacheItem = *it; - if (pFeedCacheItem->GetLastUsage() + pFeedCacheItem->GetCacheTimeSec() < tCurTime || - pFeedCacheItem->GetLastUsage() > tCurTime) + FeedCacheItem* feedCacheItem = *it; + if (feedCacheItem->GetLastUsage() + feedCacheItem->GetCacheTimeSec() < curTime || + feedCacheItem->GetLastUsage() > curTime) { - debug("Deleting %s from feed cache", pFeedCacheItem->GetUrl()); - delete pFeedCacheItem; - m_FeedCache.erase(it); - it = m_FeedCache.begin() + i; + debug("Deleting %s from feed cache", feedCacheItem->GetUrl()); + delete feedCacheItem; + m_feedCache.erase(it); + it = m_feedCache.begin() + i; } else { @@ -798,5 +798,5 @@ void FeedCoordinator::CleanupCache() } } - m_mutexDownloads.Unlock(); + m_downloadsMutex.Unlock(); } diff --git a/daemon/feed/FeedCoordinator.h b/daemon/feed/FeedCoordinator.h index fda7ffa0..9aabf233 100644 --- a/daemon/feed/FeedCoordinator.h +++ b/daemon/feed/FeedCoordinator.h @@ -47,63 +47,63 @@ private: class DownloadQueueObserver: public Observer { public: - FeedCoordinator* m_pOwner; - virtual void Update(Subject* pCaller, void* pAspect) { m_pOwner->DownloadQueueUpdate(pCaller, pAspect); } + FeedCoordinator* m_owner; + virtual void Update(Subject* caller, void* aspect) { m_owner->DownloadQueueUpdate(caller, aspect); } }; class FeedCacheItem { private: - char* m_szUrl; - int m_iCacheTimeSec; - char* m_szCacheId; - time_t m_tLastUsage; - FeedItemInfos* m_pFeedItemInfos; + char* m_url; + int m_cacheTimeSec; + char* m_cacheId; + time_t m_lastUsage; + FeedItemInfos* m_feedItemInfos; public: - FeedCacheItem(const char* szUrl, int iCacheTimeSec,const char* szCacheId, - time_t tLastUsage, FeedItemInfos* pFeedItemInfos); + FeedCacheItem(const char* url, int cacheTimeSec,const char* cacheId, + time_t lastUsage, FeedItemInfos* feedItemInfos); ~FeedCacheItem(); - const char* GetUrl() { return m_szUrl; } - int GetCacheTimeSec() { return m_iCacheTimeSec; } - const char* GetCacheId() { return m_szCacheId; } - time_t GetLastUsage() { return m_tLastUsage; } - void SetLastUsage(time_t tLastUsage) { m_tLastUsage = tLastUsage; } - FeedItemInfos* GetFeedItemInfos() { return m_pFeedItemInfos; } + const char* GetUrl() { return m_url; } + int GetCacheTimeSec() { return m_cacheTimeSec; } + const char* GetCacheId() { return m_cacheId; } + time_t GetLastUsage() { return m_lastUsage; } + void SetLastUsage(time_t lastUsage) { m_lastUsage = lastUsage; } + FeedItemInfos* GetFeedItemInfos() { return m_feedItemInfos; } }; class FilterHelper : public FeedFilterHelper { private: - RegEx* m_pSeasonEpisodeRegEx; + RegEx* m_seasonEpisodeRegEx; public: FilterHelper(); ~FilterHelper(); - virtual RegEx** GetSeasonEpisodeRegEx() { return &m_pSeasonEpisodeRegEx; }; - virtual void CalcDupeStatus(const char* szTitle, const char* szDupeKey, char* szStatusBuf, int iBufLen); + virtual RegEx** GetSeasonEpisodeRegEx() { return &m_seasonEpisodeRegEx; }; + virtual void CalcDupeStatus(const char* title, const char* dupeKey, char* statusBuf, int bufLen); }; typedef std::deque FeedCache; typedef std::list ActiveDownloads; private: - Feeds m_Feeds; - ActiveDownloads m_ActiveDownloads; - FeedHistory m_FeedHistory; - Mutex m_mutexDownloads; - DownloadQueueObserver m_DownloadQueueObserver; - bool m_bForce; - bool m_bSave; - FeedCache m_FeedCache; - FilterHelper m_FilterHelper; + Feeds m_feeds; + ActiveDownloads m_activeDownloads; + FeedHistory m_feedHistory; + Mutex m_downloadsMutex; + DownloadQueueObserver m_downloadQueueObserver; + bool m_force; + bool m_save; + FeedCache m_feedCache; + FilterHelper m_filterHelper; - void StartFeedDownload(FeedInfo* pFeedInfo, bool bForce); - void FeedCompleted(FeedDownloader* pFeedDownloader); - void FilterFeed(FeedInfo* pFeedInfo, FeedItemInfos* pFeedItemInfos); - void ProcessFeed(FeedInfo* pFeedInfo, FeedItemInfos* pFeedItemInfos, NZBList* pAddedNZBs); - NZBInfo* CreateNZBInfo(FeedInfo* pFeedInfo, FeedItemInfo* pFeedItemInfo); + void StartFeedDownload(FeedInfo* feedInfo, bool force); + void FeedCompleted(FeedDownloader* feedDownloader); + void FilterFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInfos); + void ProcessFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInfos, NZBList* addedNzbs); + NZBInfo* CreateNZBInfo(FeedInfo* feedInfo, FeedItemInfo* feedItemInfo); void ResetHangingDownloads(); - void DownloadQueueUpdate(Subject* pCaller, void* pAspect); + void DownloadQueueUpdate(Subject* caller, void* aspect); void CleanupHistory(); void CleanupCache(); void CheckSaveFeeds(); @@ -116,15 +116,15 @@ public: virtual ~FeedCoordinator(); virtual void Run(); virtual void Stop(); - void Update(Subject* pCaller, void* pAspect); - void AddFeed(FeedInfo* pFeedInfo); - bool PreviewFeed(int iID, const char* szName, const char* szUrl, const char* szFilter, bool bBacklog, - bool bPauseNzb, const char* szCategory, int iPriority, int iInterval, const char* szFeedScript, - int iCacheTimeSec, const char* szCacheId, FeedItemInfos** ppFeedItemInfos); - bool ViewFeed(int iID, FeedItemInfos** ppFeedItemInfos); - void FetchFeed(int iID); + void Update(Subject* caller, void* aspect); + void AddFeed(FeedInfo* feedInfo); + bool PreviewFeed(int id, const char* name, const char* url, const char* filter, bool backlog, + bool pauseNzb, const char* category, int priority, int interval, const char* feedScript, + int cacheTimeSec, const char* cacheId, FeedItemInfos** ppFeedItemInfos); + bool ViewFeed(int id, FeedItemInfos** ppFeedItemInfos); + void FetchFeed(int id); bool HasActiveDownloads(); - Feeds* GetFeeds() { return &m_Feeds; } + Feeds* GetFeeds() { return &m_feeds; } }; extern FeedCoordinator* g_pFeedCoordinator; @@ -132,11 +132,11 @@ extern FeedCoordinator* g_pFeedCoordinator; class FeedDownloader : public WebDownloader { private: - FeedInfo* m_pFeedInfo; + FeedInfo* m_feedInfo; public: - void SetFeedInfo(FeedInfo* pFeedInfo) { m_pFeedInfo = pFeedInfo; } - FeedInfo* GetFeedInfo() { return m_pFeedInfo; } + void SetFeedInfo(FeedInfo* feedInfo) { m_feedInfo = feedInfo; } + FeedInfo* GetFeedInfo() { return m_feedInfo; } }; #endif diff --git a/daemon/feed/FeedFile.cpp b/daemon/feed/FeedFile.cpp index 11e34257..83e491cc 100644 --- a/daemon/feed/FeedFile.cpp +++ b/daemon/feed/FeedFile.cpp @@ -51,18 +51,18 @@ using namespace MSXML; #include "Options.h" #include "Util.h" -FeedFile::FeedFile(const char* szFileName) +FeedFile::FeedFile(const char* fileName) { debug("Creating FeedFile"); - m_szFileName = strdup(szFileName); - m_pFeedItemInfos = new FeedItemInfos(); - m_pFeedItemInfos->Retain(); + m_fileName = strdup(fileName); + m_feedItemInfos = new FeedItemInfos(); + m_feedItemInfos->Retain(); #ifndef WIN32 - m_pFeedItemInfo = NULL; - m_szTagContent = NULL; - m_iTagContentLen = 0; + m_feedItemInfo = NULL; + m_tagContent = NULL; + m_tagContentLen = 0; #endif } @@ -71,29 +71,29 @@ FeedFile::~FeedFile() debug("Destroying FeedFile"); // Cleanup - free(m_szFileName); - m_pFeedItemInfos->Release(); + free(m_fileName); + m_feedItemInfos->Release(); #ifndef WIN32 - delete m_pFeedItemInfo; - free(m_szTagContent); + delete m_feedItemInfo; + free(m_tagContent); #endif } void FeedFile::LogDebugInfo() { - info(" FeedFile %s", m_szFileName); + info(" FeedFile %s", m_fileName); } -void FeedFile::AddItem(FeedItemInfo* pFeedItemInfo) +void FeedFile::AddItem(FeedItemInfo* feedItemInfo) { - m_pFeedItemInfos->Add(pFeedItemInfo); + m_feedItemInfos->Add(feedItemInfo); } -void FeedFile::ParseSubject(FeedItemInfo* pFeedItemInfo) +void FeedFile::ParseSubject(FeedItemInfo* feedItemInfo) { // if title has quatation marks we use only part within quatation marks - char* p = (char*)pFeedItemInfo->GetTitle(); + char* p = (char*)feedItemInfo->GetTitle(); char* start = strchr(p, '\"'); if (start) { @@ -115,18 +115,18 @@ void FeedFile::ParseSubject(FeedItemInfo* pFeedItemInfo) *ext = '\0'; } - pFeedItemInfo->SetFilename(filename); + feedItemInfo->SetFilename(filename); free(filename); return; } } } - pFeedItemInfo->SetFilename(pFeedItemInfo->GetTitle()); + feedItemInfo->SetFilename(feedItemInfo->GetTitle()); } #ifdef WIN32 -FeedFile* FeedFile::Create(const char* szFileName) +FeedFile* FeedFile::Create(const char* fileName) { CoInitialize(NULL); @@ -145,51 +145,51 @@ FeedFile* FeedFile::Create(const char* szFileName) doc->put_async(VARIANT_FALSE); // filename needs to be properly encoded - char* szURL = (char*)malloc(strlen(szFileName)*3 + 1); - EncodeURL(szFileName, szURL); - debug("url=\"%s\"", szURL); - _variant_t v(szURL); - free(szURL); + char* url = (char*)malloc(strlen(fileName)*3 + 1); + EncodeURL(fileName, url); + debug("url=\"%s\"", url); + _variant_t v(url); + free(url); VARIANT_BOOL success = doc->load(v); if (success == VARIANT_FALSE) { _bstr_t r(doc->GetparseError()->reason); - const char* szErrMsg = r; - error("Error parsing rss feed: %s", szErrMsg); + const char* errMsg = r; + error("Error parsing rss feed: %s", errMsg); return NULL; } - FeedFile* pFile = new FeedFile(szFileName); - if (!pFile->ParseFeed(doc)) + FeedFile* file = new FeedFile(fileName); + if (!file->ParseFeed(doc)) { - delete pFile; - pFile = NULL; + delete file; + file = NULL; } - return pFile; + return file; } -void FeedFile::EncodeURL(const char* szFilename, char* szURL) +void FeedFile::EncodeURL(const char* filename, char* url) { - while (char ch = *szFilename++) + while (char ch = *filename++) { if (('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ) { - *szURL++ = ch; + *url++ = ch; } else { - *szURL++ = '%'; + *url++ = '%'; int a = ch >> 4; - *szURL++ = a > 9 ? a - 10 + 'a' : a + '0'; + *url++ = a > 9 ? a - 10 + 'a' : a + '0'; a = ch & 0xF; - *szURL++ = a > 9 ? a - 10 + 'a' : a + '0'; + *url++ = a > 9 ? a - 10 + 'a' : a + '0'; } } - *szURL = NULL; + *url = NULL; } bool FeedFile::ParseFeed(IUnknown* nzb) @@ -202,8 +202,8 @@ bool FeedFile::ParseFeed(IUnknown* nzb) { MSXML::IXMLDOMNodePtr node = itemList->Getitem(i); - FeedItemInfo* pFeedItemInfo = new FeedItemInfo(); - AddItem(pFeedItemInfo); + FeedItemInfo* feedItemInfo = new FeedItemInfo(); + AddItem(feedItemInfo); MSXML::IXMLDOMNodePtr tag; MSXML::IXMLDOMNodePtr attr; @@ -216,8 +216,8 @@ bool FeedFile::ParseFeed(IUnknown* nzb) return false; } _bstr_t title(tag->Gettext()); - pFeedItemInfo->SetTitle(title); - ParseSubject(pFeedItemInfo); + feedItemInfo->SetTitle(title); + ParseSubject(feedItemInfo); // Wed, 26 Jun 2013 00:02:54 -0600 tag = node->selectSingleNode("pubDate"); @@ -227,7 +227,7 @@ bool FeedFile::ParseFeed(IUnknown* nzb) time_t unixtime = WebUtil::ParseRfc822DateTime(time); if (unixtime > 0) { - pFeedItemInfo->SetTime(unixtime); + feedItemInfo->SetTime(unixtime); } } @@ -236,21 +236,21 @@ bool FeedFile::ParseFeed(IUnknown* nzb) if (tag) { _bstr_t category(tag->Gettext()); - pFeedItemInfo->SetCategory(category); + feedItemInfo->SetCategory(category); } // long text tag = node->selectSingleNode("description"); if (tag) { - _bstr_t description(tag->Gettext()); + _bstr_t bdescription(tag->Gettext()); // cleanup CDATA - char* szDescription = strdup((const char*)description); - WebUtil::XmlStripTags(szDescription); - WebUtil::XmlDecode(szDescription); - WebUtil::XmlRemoveEntities(szDescription); - pFeedItemInfo->SetDescription(szDescription); - free(szDescription); + char* description = strdup((const char*)bdescription); + WebUtil::XmlStripTags(description); + WebUtil::XmlDecode(description); + WebUtil::XmlRemoveEntities(description); + feedItemInfo->SetDescription(description); + free(description); } // @@ -261,19 +261,19 @@ bool FeedFile::ParseFeed(IUnknown* nzb) if (attr) { _bstr_t url(attr->Gettext()); - pFeedItemInfo->SetUrl(url); + feedItemInfo->SetUrl(url); } attr = tag->Getattributes()->getNamedItem("length"); if (attr) { - _bstr_t size(attr->Gettext()); - long long lSize = atoll(size); - pFeedItemInfo->SetSize(lSize); + _bstr_t bsize(attr->Gettext()); + long long size = atoll(bsize); + feedItemInfo->SetSize(size); } } - if (!pFeedItemInfo->GetUrl()) + if (!feedItemInfo->GetUrl()) { // https://nzb.org/fetch/334534ce/4364564564 tag = node->selectSingleNode("link"); @@ -283,14 +283,14 @@ bool FeedFile::ParseFeed(IUnknown* nzb) return false; } _bstr_t link(tag->Gettext()); - pFeedItemInfo->SetUrl(link); + feedItemInfo->SetUrl(link); } // newznab special // - if (pFeedItemInfo->GetSize() == 0) + if (feedItemInfo->GetSize() == 0) { tag = node->selectSingleNode("newznab:attr[@name='size']"); if (tag) @@ -298,9 +298,9 @@ bool FeedFile::ParseFeed(IUnknown* nzb) attr = tag->Getattributes()->getNamedItem("value"); if (attr) { - _bstr_t size(attr->Gettext()); - long long lSize = atoll(size); - pFeedItemInfo->SetSize(lSize); + _bstr_t bsize(attr->Gettext()); + long long size = atoll(bsize); + feedItemInfo->SetSize(size); } } } @@ -312,9 +312,9 @@ bool FeedFile::ParseFeed(IUnknown* nzb) attr = tag->Getattributes()->getNamedItem("value"); if (attr) { - _bstr_t val(attr->Gettext()); - int iVal = atoi(val); - pFeedItemInfo->SetImdbId(iVal); + _bstr_t bval(attr->Gettext()); + int val = atoi(bval); + feedItemInfo->SetImdbId(val); } } @@ -325,9 +325,9 @@ bool FeedFile::ParseFeed(IUnknown* nzb) attr = tag->Getattributes()->getNamedItem("value"); if (attr) { - _bstr_t val(attr->Gettext()); - int iVal = atoi(val); - pFeedItemInfo->SetRageId(iVal); + _bstr_t bval(attr->Gettext()); + int val = atoi(bval); + feedItemInfo->SetRageId(val); } } @@ -340,7 +340,7 @@ bool FeedFile::ParseFeed(IUnknown* nzb) if (attr) { _bstr_t val(attr->Gettext()); - pFeedItemInfo->SetEpisode(val); + feedItemInfo->SetEpisode(val); } } @@ -353,7 +353,7 @@ bool FeedFile::ParseFeed(IUnknown* nzb) if (attr) { _bstr_t val(attr->Gettext()); - pFeedItemInfo->SetSeason(val); + feedItemInfo->SetSeason(val); } } @@ -365,9 +365,9 @@ bool FeedFile::ParseFeed(IUnknown* nzb) MSXML::IXMLDOMNodePtr value = node->Getattributes()->getNamedItem("value"); if (name && value) { - _bstr_t name(name->Gettext()); - _bstr_t val(value->Gettext()); - pFeedItemInfo->GetAttributes()->Add(name, val); + _bstr_t bname(name->Gettext()); + _bstr_t bval(value->Gettext()); + feedItemInfo->GetAttributes()->Add(bname, bval); } } } @@ -376,9 +376,9 @@ bool FeedFile::ParseFeed(IUnknown* nzb) #else -FeedFile* FeedFile::Create(const char* szFileName) +FeedFile* FeedFile::Create(const char* fileName) { - FeedFile* pFile = new FeedFile(szFileName); + FeedFile* file = new FeedFile(fileName); xmlSAXHandler SAX_handler = {0}; SAX_handler.startElement = reinterpret_cast(SAX_StartElement); @@ -387,18 +387,18 @@ FeedFile* FeedFile::Create(const char* szFileName) SAX_handler.error = reinterpret_cast(SAX_error); SAX_handler.getEntity = reinterpret_cast(SAX_getEntity); - pFile->m_bIgnoreNextError = false; + file->m_ignoreNextError = false; - int ret = xmlSAXUserParseFile(&SAX_handler, pFile, szFileName); + int ret = xmlSAXUserParseFile(&SAX_handler, file, fileName); if (ret != 0) { error("Failed to parse rss feed"); - delete pFile; - pFile = NULL; + delete file; + file = NULL; } - return pFile; + return file; } void FeedFile::Parse_StartElement(const char *name, const char **atts) @@ -407,66 +407,66 @@ void FeedFile::Parse_StartElement(const char *name, const char **atts) if (!strcmp("item", name)) { - delete m_pFeedItemInfo; - m_pFeedItemInfo = new FeedItemInfo(); + delete m_feedItemInfo; + m_feedItemInfo = new FeedItemInfo(); } - else if (!strcmp("enclosure", name) && m_pFeedItemInfo) + else if (!strcmp("enclosure", name) && m_feedItemInfo) { // for (; *atts; atts+=2) { if (!strcmp("url", atts[0])) { - char* szUrl = strdup(atts[1]); - WebUtil::XmlDecode(szUrl); - m_pFeedItemInfo->SetUrl(szUrl); - free(szUrl); + char* url = strdup(atts[1]); + WebUtil::XmlDecode(url); + m_feedItemInfo->SetUrl(url); + free(url); } else if (!strcmp("length", atts[0])) { - long long lSize = atoll(atts[1]); - m_pFeedItemInfo->SetSize(lSize); + long long size = atoll(atts[1]); + m_feedItemInfo->SetSize(size); } } } - else if (m_pFeedItemInfo && !strcmp("newznab:attr", name) && + else if (m_feedItemInfo && !strcmp("newznab:attr", name) && atts[0] && atts[1] && atts[2] && atts[3] && !strcmp("name", atts[0]) && !strcmp("value", atts[2])) { - m_pFeedItemInfo->GetAttributes()->Add(atts[1], atts[3]); + m_feedItemInfo->GetAttributes()->Add(atts[1], atts[3]); // - if (m_pFeedItemInfo->GetSize() == 0 && + if (m_feedItemInfo->GetSize() == 0 && !strcmp("size", atts[1])) { - long long lSize = atoll(atts[3]); - m_pFeedItemInfo->SetSize(lSize); + long long size = atoll(atts[3]); + m_feedItemInfo->SetSize(size); } // else if (!strcmp("imdb", atts[1])) { - m_pFeedItemInfo->SetImdbId(atoi(atts[3])); + m_feedItemInfo->SetImdbId(atoi(atts[3])); } // else if (!strcmp("rageid", atts[1])) { - m_pFeedItemInfo->SetRageId(atoi(atts[3])); + m_feedItemInfo->SetRageId(atoi(atts[3])); } // // else if (!strcmp("episode", atts[1])) { - m_pFeedItemInfo->SetEpisode(atts[3]); + m_feedItemInfo->SetEpisode(atts[3]); } // // else if (!strcmp("season", atts[1])) { - m_pFeedItemInfo->SetSeason(atts[3]); + m_feedItemInfo->SetSeason(atts[3]); } } } @@ -476,43 +476,43 @@ void FeedFile::Parse_EndElement(const char *name) if (!strcmp("item", name)) { // Close the file element, add the new file to file-list - AddItem(m_pFeedItemInfo); - m_pFeedItemInfo = NULL; + AddItem(m_feedItemInfo); + m_feedItemInfo = NULL; } - else if (!strcmp("title", name) && m_pFeedItemInfo) + else if (!strcmp("title", name) && m_feedItemInfo) { - m_pFeedItemInfo->SetTitle(m_szTagContent); + m_feedItemInfo->SetTitle(m_tagContent); ResetTagContent(); - ParseSubject(m_pFeedItemInfo); + ParseSubject(m_feedItemInfo); } - else if (!strcmp("link", name) && m_pFeedItemInfo && - (!m_pFeedItemInfo->GetUrl() || strlen(m_pFeedItemInfo->GetUrl()) == 0)) + else if (!strcmp("link", name) && m_feedItemInfo && + (!m_feedItemInfo->GetUrl() || strlen(m_feedItemInfo->GetUrl()) == 0)) { - m_pFeedItemInfo->SetUrl(m_szTagContent); + m_feedItemInfo->SetUrl(m_tagContent); ResetTagContent(); } - else if (!strcmp("category", name) && m_pFeedItemInfo) + else if (!strcmp("category", name) && m_feedItemInfo) { - m_pFeedItemInfo->SetCategory(m_szTagContent); + m_feedItemInfo->SetCategory(m_tagContent); ResetTagContent(); } - else if (!strcmp("description", name) && m_pFeedItemInfo) + else if (!strcmp("description", name) && m_feedItemInfo) { // cleanup CDATA - char* szDescription = strdup(m_szTagContent); - WebUtil::XmlStripTags(szDescription); - WebUtil::XmlDecode(szDescription); - WebUtil::XmlRemoveEntities(szDescription); - m_pFeedItemInfo->SetDescription(szDescription); - free(szDescription); + char* description = strdup(m_tagContent); + WebUtil::XmlStripTags(description); + WebUtil::XmlDecode(description); + WebUtil::XmlRemoveEntities(description); + m_feedItemInfo->SetDescription(description); + free(description); ResetTagContent(); } - else if (!strcmp("pubDate", name) && m_pFeedItemInfo) + else if (!strcmp("pubDate", name) && m_feedItemInfo) { - time_t unixtime = WebUtil::ParseRfc822DateTime(m_szTagContent); + time_t unixtime = WebUtil::ParseRfc822DateTime(m_tagContent); if (unixtime > 0) { - m_pFeedItemInfo->SetTime(unixtime); + m_feedItemInfo->SetTime(unixtime); } ResetTagContent(); } @@ -520,30 +520,30 @@ void FeedFile::Parse_EndElement(const char *name) void FeedFile::Parse_Content(const char *buf, int len) { - m_szTagContent = (char*)realloc(m_szTagContent, m_iTagContentLen + len + 1); - strncpy(m_szTagContent + m_iTagContentLen, buf, len); - m_iTagContentLen += len; - m_szTagContent[m_iTagContentLen] = '\0'; + m_tagContent = (char*)realloc(m_tagContent, m_tagContentLen + len + 1); + strncpy(m_tagContent + m_tagContentLen, buf, len); + m_tagContentLen += len; + m_tagContent[m_tagContentLen] = '\0'; } void FeedFile::ResetTagContent() { - free(m_szTagContent); - m_szTagContent = NULL; - m_iTagContentLen = 0; + free(m_tagContent); + m_tagContent = NULL; + m_tagContentLen = 0; } -void FeedFile::SAX_StartElement(FeedFile* pFile, const char *name, const char **atts) +void FeedFile::SAX_StartElement(FeedFile* file, const char *name, const char **atts) { - pFile->Parse_StartElement(name, atts); + file->Parse_StartElement(name, atts); } -void FeedFile::SAX_EndElement(FeedFile* pFile, const char *name) +void FeedFile::SAX_EndElement(FeedFile* file, const char *name) { - pFile->Parse_EndElement(name); + file->Parse_EndElement(name); } -void FeedFile::SAX_characters(FeedFile* pFile, const char * xmlstr, int len) +void FeedFile::SAX_characters(FeedFile* file, const char * xmlstr, int len) { char* str = (char*)xmlstr; @@ -581,39 +581,39 @@ void FeedFile::SAX_characters(FeedFile* pFile, const char * xmlstr, int len) if (newlen > 0) { // interpret tag content - pFile->Parse_Content(str + off, newlen); + file->Parse_Content(str + off, newlen); } } -void* FeedFile::SAX_getEntity(FeedFile* pFile, const char * name) +void* FeedFile::SAX_getEntity(FeedFile* file, const char * name) { xmlEntityPtr e = xmlGetPredefinedEntity((xmlChar* )name); if (!e) { warn("entity not found"); - pFile->m_bIgnoreNextError = true; + file->m_ignoreNextError = true; } return e; } -void FeedFile::SAX_error(FeedFile* pFile, const char *msg, ...) +void FeedFile::SAX_error(FeedFile* file, const char *msg, ...) { - if (pFile->m_bIgnoreNextError) + if (file->m_ignoreNextError) { - pFile->m_bIgnoreNextError = false; + file->m_ignoreNextError = false; return; } va_list argp; va_start(argp, msg); - char szErrMsg[1024]; - vsnprintf(szErrMsg, sizeof(szErrMsg), msg, argp); - szErrMsg[1024-1] = '\0'; + char errMsg[1024]; + vsnprintf(errMsg, sizeof(errMsg), msg, argp); + errMsg[1024-1] = '\0'; va_end(argp); // remove trailing CRLF - for (char* pend = szErrMsg + strlen(szErrMsg) - 1; pend >= szErrMsg && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; - error("Error parsing rss feed: %s", szErrMsg); + for (char* pend = errMsg + strlen(errMsg) - 1; pend >= errMsg && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; + error("Error parsing rss feed: %s", errMsg); } #endif diff --git a/daemon/feed/FeedFile.h b/daemon/feed/FeedFile.h index 56a4ca3e..6a1466e0 100644 --- a/daemon/feed/FeedFile.h +++ b/daemon/feed/FeedFile.h @@ -33,26 +33,26 @@ class FeedFile { private: - FeedItemInfos* m_pFeedItemInfos; - char* m_szFileName; + FeedItemInfos* m_feedItemInfos; + char* m_fileName; - FeedFile(const char* szFileName); - void AddItem(FeedItemInfo* pFeedItemInfo); - void ParseSubject(FeedItemInfo* pFeedItemInfo); + FeedFile(const char* fileName); + void AddItem(FeedItemInfo* feedItemInfo); + void ParseSubject(FeedItemInfo* feedItemInfo); #ifdef WIN32 bool ParseFeed(IUnknown* nzb); - static void EncodeURL(const char* szFilename, char* szURL); + static void EncodeURL(const char* filename, char* url); #else - FeedItemInfo* m_pFeedItemInfo; - char* m_szTagContent; - int m_iTagContentLen; - bool m_bIgnoreNextError; + FeedItemInfo* m_feedItemInfo; + char* m_tagContent; + int m_tagContentLen; + bool m_ignoreNextError; - static void SAX_StartElement(FeedFile* pFile, const char *name, const char **atts); - static void SAX_EndElement(FeedFile* pFile, const char *name); - static void SAX_characters(FeedFile* pFile, const char * xmlstr, int len); - static void* SAX_getEntity(FeedFile* pFile, const char * name); - static void SAX_error(FeedFile* pFile, const char *msg, ...); + static void SAX_StartElement(FeedFile* file, const char *name, const char **atts); + static void SAX_EndElement(FeedFile* file, const char *name); + static void SAX_characters(FeedFile* file, const char * xmlstr, int len); + static void* SAX_getEntity(FeedFile* file, const char * name); + static void SAX_error(FeedFile* file, const char *msg, ...); void Parse_StartElement(const char *name, const char **atts); void Parse_EndElement(const char *name); void Parse_Content(const char *buf, int len); @@ -61,8 +61,8 @@ private: public: virtual ~FeedFile(); - static FeedFile* Create(const char* szFileName); - FeedItemInfos* GetFeedItemInfos() { return m_pFeedItemInfos; } + static FeedFile* Create(const char* fileName); + FeedItemInfos* GetFeedItemInfos() { return m_feedItemInfos; } void LogDebugInfo(); }; diff --git a/daemon/feed/FeedFilter.cpp b/daemon/feed/FeedFilter.cpp index 3a64f6c4..f6079c3f 100644 --- a/daemon/feed/FeedFilter.cpp +++ b/daemon/feed/FeedFilter.cpp @@ -44,35 +44,35 @@ FeedFilter::Term::Term() { - m_szField = NULL; - m_szParam = NULL; - m_bFloat = false; - m_iIntParam = 0; + m_field = NULL; + m_param = NULL; + m_float = false; + m_intParam = 0; m_fFloatParam = 0.0; - m_pRegEx = NULL; - m_pRefValues = NULL; + m_regEx = NULL; + m_refValues = NULL; } FeedFilter::Term::~Term() { - free(m_szField); - free(m_szParam); - delete m_pRegEx; + free(m_field); + free(m_param); + delete m_regEx; } -bool FeedFilter::Term::Match(FeedItemInfo* pFeedItemInfo) +bool FeedFilter::Term::Match(FeedItemInfo* feedItemInfo) { - const char* szStrValue = NULL; - long long iIntValue = 0; + const char* strValue = NULL; + long long intValue = 0; - if (!GetFieldData(m_szField, pFeedItemInfo, &szStrValue, &iIntValue)) + if (!GetFieldData(m_field, feedItemInfo, &strValue, &intValue)) { return false; } - bool bMatch = MatchValue(szStrValue, iIntValue); + bool match = MatchValue(strValue, intValue); - if (m_bPositive != bMatch) + if (m_positive != match) { return false; } @@ -80,87 +80,87 @@ bool FeedFilter::Term::Match(FeedItemInfo* pFeedItemInfo) return true; } -bool FeedFilter::Term::MatchValue(const char* szStrValue, long long iIntValue) +bool FeedFilter::Term::MatchValue(const char* strValue, long long intValue) { - double fFloatValue = (double)iIntValue; - char szIntBuf[100]; + double fFloatValue = (double)intValue; + char intBuf[100]; - if (m_eCommand < fcEqual && !szStrValue) + if (m_command < fcEqual && !strValue) { - snprintf(szIntBuf, 100, "%lld", iIntValue); - szIntBuf[100-1] = '\0'; - szStrValue = szIntBuf; + snprintf(intBuf, 100, "%lld", intValue); + intBuf[100-1] = '\0'; + strValue = intBuf; } - else if (m_eCommand >= fcEqual && szStrValue) + else if (m_command >= fcEqual && strValue) { - fFloatValue = atof(szStrValue); - iIntValue = (long long)fFloatValue; + fFloatValue = atof(strValue); + intValue = (long long)fFloatValue; } - switch (m_eCommand) + switch (m_command) { case fcText: - return MatchText(szStrValue); + return MatchText(strValue); case fcRegex: - return MatchRegex(szStrValue); + return MatchRegex(strValue); case fcEqual: - return m_bFloat ? fFloatValue == m_fFloatParam : iIntValue == m_iIntParam; + return m_float ? fFloatValue == m_fFloatParam : intValue == m_intParam; case fcLess: - return m_bFloat ? fFloatValue < m_fFloatParam : iIntValue < m_iIntParam; + return m_float ? fFloatValue < m_fFloatParam : intValue < m_intParam; case fcLessEqual: - return m_bFloat ? fFloatValue <= m_fFloatParam : iIntValue <= m_iIntParam; + return m_float ? fFloatValue <= m_fFloatParam : intValue <= m_intParam; case fcGreater: - return m_bFloat ? fFloatValue > m_fFloatParam : iIntValue > m_iIntParam; + return m_float ? fFloatValue > m_fFloatParam : intValue > m_intParam; case fcGreaterEqual: - return m_bFloat ? fFloatValue >= m_fFloatParam : iIntValue >= m_iIntParam; + return m_float ? fFloatValue >= m_fFloatParam : intValue >= m_intParam; default: return false; } } -bool FeedFilter::Term::MatchText(const char* szStrValue) +bool FeedFilter::Term::MatchText(const char* strValue) { const char* WORD_SEPARATORS = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; // first check if we should make word-search or substring-search - int iParamLen = strlen(m_szParam); - bool bSubstr = iParamLen >= 2 && m_szParam[0] == '*' && m_szParam[iParamLen-1] == '*'; - if (!bSubstr) + int paramLen = strlen(m_param); + bool substr = paramLen >= 2 && m_param[0] == '*' && m_param[paramLen-1] == '*'; + if (!substr) { - for (const char* p = m_szParam; *p; p++) + for (const char* p = m_param; *p; p++) { char ch = *p; if (strchr(WORD_SEPARATORS, ch) && ch != '*' && ch != '?' && ch != '#') { - bSubstr = true; + substr = true; break; } } } - bool bMatch = false; + bool match = false; - if (!bSubstr) + if (!substr) { // Word-search // split szStrValue into tokens - Tokenizer tok(szStrValue, WORD_SEPARATORS); - while (const char* szWord = tok.Next()) + Tokenizer tok(strValue, WORD_SEPARATORS); + while (const char* word = tok.Next()) { - WildMask mask(m_szParam, m_pRefValues != NULL); - bMatch = mask.Match(szWord); - if (bMatch) + WildMask mask(m_param, m_refValues != NULL); + match = mask.Match(word); + if (match) { - FillWildMaskRefValues(szWord, &mask, 0); + FillWildMaskRefValues(word, &mask, 0); break; } } @@ -169,101 +169,101 @@ bool FeedFilter::Term::MatchText(const char* szStrValue) { // Substring-search - int iRefOffset = 1; - const char* szFormat = "*%s*"; - if (iParamLen >= 2 && m_szParam[0] == '*' && m_szParam[iParamLen-1] == '*') + int refOffset = 1; + const char* format = "*%s*"; + if (paramLen >= 2 && m_param[0] == '*' && m_param[paramLen-1] == '*') { - szFormat = "%s"; - iRefOffset = 0; + format = "%s"; + refOffset = 0; } - else if (iParamLen >= 1 && m_szParam[0] == '*') + else if (paramLen >= 1 && m_param[0] == '*') { - szFormat = "%s*"; - iRefOffset = 0; + format = "%s*"; + refOffset = 0; } - else if (iParamLen >= 1 && m_szParam[iParamLen-1] == '*') + else if (paramLen >= 1 && m_param[paramLen-1] == '*') { - szFormat = "*%s"; + format = "*%s"; } - int iMaskLen = strlen(m_szParam) + 2 + 1; - char* szMask = (char*)malloc(iMaskLen); - snprintf(szMask, iMaskLen, szFormat, m_szParam); - szMask[iMaskLen-1] = '\0'; + int patlen = strlen(m_param) + 2 + 1; + char* pattern = (char*)malloc(patlen); + snprintf(pattern, patlen, format, m_param); + pattern[patlen-1] = '\0'; - WildMask mask(szMask, m_pRefValues != NULL); - bMatch = mask.Match(szStrValue); + WildMask mask(pattern, m_refValues != NULL); + match = mask.Match(strValue); - if (bMatch) + if (match) { - FillWildMaskRefValues(szStrValue, &mask, iRefOffset); + FillWildMaskRefValues(strValue, &mask, refOffset); } - free(szMask); + free(pattern); } - return bMatch; + return match; } -bool FeedFilter::Term::MatchRegex(const char* szStrValue) +bool FeedFilter::Term::MatchRegex(const char* strValue) { - if (!m_pRegEx) + if (!m_regEx) { - m_pRegEx = new RegEx(m_szParam, m_pRefValues == NULL ? 0 : 100); + m_regEx = new RegEx(m_param, m_refValues == NULL ? 0 : 100); } - bool bFound = m_pRegEx->Match(szStrValue); - if (bFound) + bool found = m_regEx->Match(strValue); + if (found) { - FillRegExRefValues(szStrValue, m_pRegEx); + FillRegExRefValues(strValue, m_regEx); } - return bFound; + return found; } -bool FeedFilter::Term::Compile(char* szToken) +bool FeedFilter::Term::Compile(char* token) { - debug("Token: %s", szToken); + debug("Token: %s", token); - char ch = szToken[0]; + char ch = token[0]; - m_bPositive = ch != '-'; + m_positive = ch != '-'; if (ch == '-' || ch == '+') { - szToken++; - ch = szToken[0]; + token++; + ch = token[0]; } - char ch2= szToken[1]; + char ch2= token[1]; if ((ch == '(' || ch == ')' || ch == '|') && (ch2 == ' ' || ch2 == '\0')) { switch (ch) { case '(': - m_eCommand = fcOpeningBrace; + m_command = fcOpeningBrace; return true; case ')': - m_eCommand = fcClosingBrace; + m_command = fcClosingBrace; return true; case '|': - m_eCommand = fcOrOperator; + m_command = fcOrOperator; return true; } } - char *szField = NULL; - m_eCommand = fcText; + char *field = NULL; + m_command = fcText; - char* szColon = NULL; + char* colon = NULL; if (ch != '@' && ch != '$' && ch != '<' && ch != '>' && ch != '=') { - szColon = strchr(szToken, ':'); + colon = strchr(token, ':'); } - if (szColon) + if (colon) { - szField = szToken; - szColon[0] = '\0'; - szToken = szColon + 1; - ch = szToken[0]; + field = token; + colon[0] = '\0'; + token = colon + 1; + ch = token[0]; } if (ch == '\0') @@ -271,60 +271,60 @@ bool FeedFilter::Term::Compile(char* szToken) return false; } - ch2= szToken[1]; + ch2= token[1]; if (ch == '@') { - m_eCommand = fcText; - szToken++; + m_command = fcText; + token++; } else if (ch == '$') { - m_eCommand = fcRegex; - szToken++; + m_command = fcRegex; + token++; } else if (ch == '=') { - m_eCommand = fcEqual; - szToken++; + m_command = fcEqual; + token++; } else if (ch == '<' && ch2 == '=') { - m_eCommand = fcLessEqual; - szToken += 2; + m_command = fcLessEqual; + token += 2; } else if (ch == '>' && ch2 == '=') { - m_eCommand = fcGreaterEqual; - szToken += 2; + m_command = fcGreaterEqual; + token += 2; } else if (ch == '<') { - m_eCommand = fcLess; - szToken++; + m_command = fcLess; + token++; } else if (ch == '>') { - m_eCommand = fcGreater; - szToken++; + m_command = fcGreater; + token++; } - debug("%s, Field: %s, Command: %i, Param: %s", (m_bPositive ? "Positive" : "Negative"), szField, m_eCommand, szToken); + debug("%s, Field: %s, Command: %i, Param: %s", (m_positive ? "Positive" : "Negative"), field, m_command, token); - const char* szStrValue; - long long iIntValue; - if (!GetFieldData(szField, NULL, &szStrValue, &iIntValue)) + const char* strValue; + long long intValue; + if (!GetFieldData(field, NULL, &strValue, &intValue)) { return false; } - if (szField && !ParseParam(szField, szToken)) + if (field && !ParseParam(field, token)) { return false; } - m_szField = szField ? strdup(szField) : NULL; - m_szParam = strdup(szToken); + m_field = field ? strdup(field) : NULL; + m_param = strdup(token); return true; } @@ -332,93 +332,93 @@ bool FeedFilter::Term::Compile(char* szToken) /* * If pFeedItemInfo is NULL, only field name is validated */ -bool FeedFilter::Term::GetFieldData(const char* szField, FeedItemInfo* pFeedItemInfo, +bool FeedFilter::Term::GetFieldData(const char* field, FeedItemInfo* feedItemInfo, const char** StrValue, long long* IntValue) { *StrValue = NULL; *IntValue = 0; - if (!szField || !strcasecmp(szField, "title")) + if (!field || !strcasecmp(field, "title")) { - *StrValue = pFeedItemInfo ? pFeedItemInfo->GetTitle() : NULL; + *StrValue = feedItemInfo ? feedItemInfo->GetTitle() : NULL; return true; } - else if (!strcasecmp(szField, "filename")) + else if (!strcasecmp(field, "filename")) { - *StrValue = pFeedItemInfo ? pFeedItemInfo->GetFilename() : NULL; + *StrValue = feedItemInfo ? feedItemInfo->GetFilename() : NULL; return true; } - else if (!strcasecmp(szField, "category")) + else if (!strcasecmp(field, "category")) { - *StrValue = pFeedItemInfo ? pFeedItemInfo->GetCategory() : NULL; + *StrValue = feedItemInfo ? feedItemInfo->GetCategory() : NULL; return true; } - else if (!strcasecmp(szField, "link") || !strcasecmp(szField, "url")) + else if (!strcasecmp(field, "link") || !strcasecmp(field, "url")) { - *StrValue = pFeedItemInfo ? pFeedItemInfo->GetUrl() : NULL; + *StrValue = feedItemInfo ? feedItemInfo->GetUrl() : NULL; return true; } - else if (!strcasecmp(szField, "size")) + else if (!strcasecmp(field, "size")) { - *IntValue = pFeedItemInfo ? pFeedItemInfo->GetSize() : 0; + *IntValue = feedItemInfo ? feedItemInfo->GetSize() : 0; return true; } - else if (!strcasecmp(szField, "age")) + else if (!strcasecmp(field, "age")) { - *IntValue = pFeedItemInfo ? time(NULL) - pFeedItemInfo->GetTime() : 0; + *IntValue = feedItemInfo ? time(NULL) - feedItemInfo->GetTime() : 0; return true; } - else if (!strcasecmp(szField, "imdbid")) + else if (!strcasecmp(field, "imdbid")) { - *IntValue = pFeedItemInfo ? pFeedItemInfo->GetImdbId() : 0; + *IntValue = feedItemInfo ? feedItemInfo->GetImdbId() : 0; return true; } - else if (!strcasecmp(szField, "rageid")) + else if (!strcasecmp(field, "rageid")) { - *IntValue = pFeedItemInfo ? pFeedItemInfo->GetRageId() : 0; + *IntValue = feedItemInfo ? feedItemInfo->GetRageId() : 0; return true; } - else if (!strcasecmp(szField, "description")) + else if (!strcasecmp(field, "description")) { - *StrValue = pFeedItemInfo ? pFeedItemInfo->GetDescription() : NULL; + *StrValue = feedItemInfo ? feedItemInfo->GetDescription() : NULL; return true; } - else if (!strcasecmp(szField, "season")) + else if (!strcasecmp(field, "season")) { - *IntValue = pFeedItemInfo ? pFeedItemInfo->GetSeasonNum() : 0; + *IntValue = feedItemInfo ? feedItemInfo->GetSeasonNum() : 0; return true; } - else if (!strcasecmp(szField, "episode")) + else if (!strcasecmp(field, "episode")) { - *IntValue = pFeedItemInfo ? pFeedItemInfo->GetEpisodeNum() : 0; + *IntValue = feedItemInfo ? feedItemInfo->GetEpisodeNum() : 0; return true; } - else if (!strcasecmp(szField, "priority")) + else if (!strcasecmp(field, "priority")) { - *IntValue = pFeedItemInfo ? pFeedItemInfo->GetPriority() : 0; + *IntValue = feedItemInfo ? feedItemInfo->GetPriority() : 0; return true; } - else if (!strcasecmp(szField, "dupekey")) + else if (!strcasecmp(field, "dupekey")) { - *StrValue = pFeedItemInfo ? pFeedItemInfo->GetDupeKey() : NULL; + *StrValue = feedItemInfo ? feedItemInfo->GetDupeKey() : NULL; return true; } - else if (!strcasecmp(szField, "dupescore")) + else if (!strcasecmp(field, "dupescore")) { - *IntValue = pFeedItemInfo ? pFeedItemInfo->GetDupeScore() : 0; + *IntValue = feedItemInfo ? feedItemInfo->GetDupeScore() : 0; return true; } - else if (!strcasecmp(szField, "dupestatus")) + else if (!strcasecmp(field, "dupestatus")) { - *StrValue = pFeedItemInfo ? pFeedItemInfo->GetDupeStatus() : NULL; + *StrValue = feedItemInfo ? feedItemInfo->GetDupeStatus() : NULL; return true; } - else if (!strncasecmp(szField, "attr-", 5)) + else if (!strncasecmp(field, "attr-", 5)) { - if (pFeedItemInfo) + if (feedItemInfo) { - FeedItemInfo::Attr* pAttr = pFeedItemInfo->GetAttributes()->Find(szField + 5); - *StrValue = pAttr ? pAttr->GetValue() : NULL; + FeedItemInfo::Attr* attr = feedItemInfo->GetAttributes()->Find(field + 5); + *StrValue = attr ? attr->GetValue() : NULL; } return true; } @@ -426,43 +426,43 @@ bool FeedFilter::Term::GetFieldData(const char* szField, FeedItemInfo* pFeedItem return false; } -bool FeedFilter::Term::ParseParam(const char* szField, const char* szParam) +bool FeedFilter::Term::ParseParam(const char* field, const char* param) { - if (!strcasecmp(szField, "size")) + if (!strcasecmp(field, "size")) { - return ParseSizeParam(szParam); + return ParseSizeParam(param); } - else if (!strcasecmp(szField, "age")) + else if (!strcasecmp(field, "age")) { - return ParseAgeParam(szParam); + return ParseAgeParam(param); } - else if (m_eCommand >= fcEqual) + else if (m_command >= fcEqual) { - return ParseNumericParam(szParam); + return ParseNumericParam(param); } return true; } -bool FeedFilter::Term::ParseSizeParam(const char* szParam) +bool FeedFilter::Term::ParseSizeParam(const char* param) { - double fParam = atof(szParam); + double fParam = atof(param); const char* p; - for (p = szParam; *p && ((*p >= '0' && *p <='9') || *p == '.'); p++) ; + for (p = param; *p && ((*p >= '0' && *p <='9') || *p == '.'); p++) ; if (*p) { if (!strcasecmp(p, "K") || !strcasecmp(p, "KB")) { - m_iIntParam = (long long)(fParam*1024); + m_intParam = (long long)(fParam*1024); } else if (!strcasecmp(p, "M") || !strcasecmp(p, "MB")) { - m_iIntParam = (long long)(fParam*1024*1024); + m_intParam = (long long)(fParam*1024*1024); } else if (!strcasecmp(p, "G") || !strcasecmp(p, "GB")) { - m_iIntParam = (long long)(fParam*1024*1024*1024); + m_intParam = (long long)(fParam*1024*1024*1024); } else { @@ -471,34 +471,34 @@ bool FeedFilter::Term::ParseSizeParam(const char* szParam) } else { - m_iIntParam = (long long)fParam; + m_intParam = (long long)fParam; } return true; } -bool FeedFilter::Term::ParseAgeParam(const char* szParam) +bool FeedFilter::Term::ParseAgeParam(const char* param) { - double fParam = atof(szParam); + double fParam = atof(param); const char* p; - for (p = szParam; *p && ((*p >= '0' && *p <='9') || *p == '.'); p++) ; + for (p = param; *p && ((*p >= '0' && *p <='9') || *p == '.'); p++) ; if (*p) { if (!strcasecmp(p, "m")) { // minutes - m_iIntParam = (long long)(fParam*60); + m_intParam = (long long)(fParam*60); } else if (!strcasecmp(p, "h")) { // hours - m_iIntParam = (long long)(fParam*60*60); + m_intParam = (long long)(fParam*60*60); } else if (!strcasecmp(p, "d")) { // days - m_iIntParam = (long long)(fParam*60*60*24); + m_intParam = (long long)(fParam*60*60*24); } else { @@ -508,20 +508,20 @@ bool FeedFilter::Term::ParseAgeParam(const char* szParam) else { // days by default - m_iIntParam = (long long)(fParam*60*60*24); + m_intParam = (long long)(fParam*60*60*24); } return true; } -bool FeedFilter::Term::ParseNumericParam(const char* szParam) +bool FeedFilter::Term::ParseNumericParam(const char* param) { - m_fFloatParam = atof(szParam); - m_iIntParam = (long long)m_fFloatParam; - m_bFloat = strchr(szParam, '.'); + m_fFloatParam = atof(param); + m_intParam = (long long)m_fFloatParam; + m_float = strchr(param, '.'); const char* p; - for (p = szParam; *p && ((*p >= '0' && *p <='9') || *p == '.' || *p == '-') ; p++) ; + for (p = param; *p && ((*p >= '0' && *p <='9') || *p == '.' || *p == '-') ; p++) ; if (*p) { return false; @@ -530,200 +530,200 @@ bool FeedFilter::Term::ParseNumericParam(const char* szParam) return true; } -void FeedFilter::Term::FillWildMaskRefValues(const char* szStrValue, WildMask* pMask, int iRefOffset) +void FeedFilter::Term::FillWildMaskRefValues(const char* strValue, WildMask* mask, int refOffset) { - if (!m_pRefValues) + if (!m_refValues) { return; } - for (int i = iRefOffset; i < pMask->GetMatchCount(); i++) + for (int i = refOffset; i < mask->GetMatchCount(); i++) { - int iLen = pMask->GetMatchLen(i); - char* szValue = (char*)malloc(iLen + 1); - strncpy(szValue, szStrValue + pMask->GetMatchStart(i), iLen); - szValue[iLen] = '\0'; + int len = mask->GetMatchLen(i); + char* value = (char*)malloc(len + 1); + strncpy(value, strValue + mask->GetMatchStart(i), len); + value[len] = '\0'; - m_pRefValues->push_back(szValue); + m_refValues->push_back(value); } } -void FeedFilter::Term::FillRegExRefValues(const char* szStrValue, RegEx* pRegEx) +void FeedFilter::Term::FillRegExRefValues(const char* strValue, RegEx* regEx) { - if (!m_pRefValues) + if (!m_refValues) { return; } - for (int i = 1; i < pRegEx->GetMatchCount(); i++) + for (int i = 1; i < regEx->GetMatchCount(); i++) { - int iLen = pRegEx->GetMatchLen(i); - char* szValue = (char*)malloc(iLen + 1); - strncpy(szValue, szStrValue + pRegEx->GetMatchStart(i), iLen); - szValue[iLen] = '\0'; + int len = regEx->GetMatchLen(i); + char* value = (char*)malloc(len + 1); + strncpy(value, strValue + regEx->GetMatchStart(i), len); + value[len] = '\0'; - m_pRefValues->push_back(szValue); + m_refValues->push_back(value); } } FeedFilter::Rule::Rule() { - m_eCommand = frAccept; - m_bIsValid = false; - m_szCategory = NULL; - m_iPriority = 0; - m_iAddPriority = 0; - m_bPause = false; - m_szDupeKey = NULL; - m_szAddDupeKey = NULL; - m_iDupeScore = 0; - m_iAddDupeScore = 0; - m_eDupeMode = dmScore; - m_szRageId = NULL; - m_szSeries = NULL; - m_bHasCategory = false; - m_bHasPriority = false; - m_bHasAddPriority = false; - m_bHasPause = false; - m_bHasDupeScore = false; - m_bHasAddDupeScore = false; - m_bHasDupeKey = false; - m_bHasAddDupeKey = false; - m_bHasDupeMode = false; - m_bHasRageId = false; - m_bHasSeries = false; - m_bPatCategory = false; - m_bPatDupeKey = false; - m_bPatAddDupeKey = false; - m_szPatCategory = NULL; - m_szPatDupeKey = NULL; - m_szPatAddDupeKey = NULL; + m_command = frAccept; + m_isValid = false; + m_category = NULL; + m_priority = 0; + m_addPriority = 0; + m_pause = false; + m_dupeKey = NULL; + m_addDupeKey = NULL; + m_dupeScore = 0; + m_addDupeScore = 0; + m_dupeMode = dmScore; + m_rageId = NULL; + m_series = NULL; + m_hasCategory = false; + m_hasPriority = false; + m_hasAddPriority = false; + m_hasPause = false; + m_hasDupeScore = false; + m_hasAddDupeScore = false; + m_hasDupeKey = false; + m_hasAddDupeKey = false; + m_hasDupeMode = false; + m_hasRageId = false; + m_hasSeries = false; + m_hasPatCategory = false; + m_hasPatDupeKey = false; + m_hasPatAddDupeKey = false; + m_patCategory = NULL; + m_patDupeKey = NULL; + m_patAddDupeKey = NULL; } FeedFilter::Rule::~Rule() { - free(m_szCategory); - free(m_szDupeKey); - free(m_szAddDupeKey); - free(m_szRageId); - free(m_szSeries); - free(m_szPatCategory); - free(m_szPatDupeKey); - free(m_szPatAddDupeKey); + free(m_category); + free(m_dupeKey); + free(m_addDupeKey); + free(m_rageId); + free(m_series); + free(m_patCategory); + free(m_patDupeKey); + free(m_patAddDupeKey); - for (TermList::iterator it = m_Terms.begin(); it != m_Terms.end(); it++) + for (TermList::iterator it = m_terms.begin(); it != m_terms.end(); it++) { delete *it; } - for (RefValues::iterator it = m_RefValues.begin(); it != m_RefValues.end(); it++) + for (RefValues::iterator it = m_refValues.begin(); it != m_refValues.end(); it++) { delete *it; } } -void FeedFilter::Rule::Compile(char* szRule) +void FeedFilter::Rule::Compile(char* rule) { - debug("Compiling rule: %s", szRule); + debug("Compiling rule: %s", rule); - m_bIsValid = true; + m_isValid = true; - char* szFilter3 = Util::Trim(szRule); + char* filter3 = Util::Trim(rule); - char* szTerm = CompileCommand(szFilter3); - if (!szTerm) + char* term = CompileCommand(filter3); + if (!term) { - m_bIsValid = false; + m_isValid = false; return; } - if (m_eCommand == frComment) + if (m_command == frComment) { return; } - szTerm = Util::Trim(szTerm); + term = Util::Trim(term); - for (char* p = szTerm; *p && m_bIsValid; p++) + for (char* p = term; *p && m_isValid; p++) { char ch = *p; if (ch == ' ') { *p = '\0'; - m_bIsValid = CompileTerm(szTerm); - szTerm = p + 1; - while (*szTerm == ' ') szTerm++; - p = szTerm; + m_isValid = CompileTerm(term); + term = p + 1; + while (*term == ' ') term++; + p = term; } } - m_bIsValid = m_bIsValid && CompileTerm(szTerm); + m_isValid = m_isValid && CompileTerm(term); - if (m_bIsValid && m_bPatCategory) + if (m_isValid && m_hasPatCategory) { - m_szPatCategory = m_szCategory; - m_szCategory = NULL; + m_patCategory = m_category; + m_category = NULL; } - if (m_bIsValid && m_bPatDupeKey) + if (m_isValid && m_hasPatDupeKey) { - m_szPatDupeKey = m_szDupeKey; - m_szDupeKey = NULL; + m_patDupeKey = m_dupeKey; + m_dupeKey = NULL; } - if (m_bIsValid && m_bPatAddDupeKey) + if (m_isValid && m_hasPatAddDupeKey) { - m_szPatAddDupeKey = m_szAddDupeKey; - m_szAddDupeKey = NULL; + m_patAddDupeKey = m_addDupeKey; + m_addDupeKey = NULL; } } /* Checks if the rule starts with command and compiles it. * Returns a pointer to the next (first) term or NULL in a case of compilation error. */ -char* FeedFilter::Rule::CompileCommand(char* szRule) +char* FeedFilter::Rule::CompileCommand(char* rule) { - if (!strncasecmp(szRule, "A:", 2) || !strncasecmp(szRule, "Accept:", 7) || - !strncasecmp(szRule, "A(", 2) || !strncasecmp(szRule, "Accept(", 7)) + if (!strncasecmp(rule, "A:", 2) || !strncasecmp(rule, "Accept:", 7) || + !strncasecmp(rule, "A(", 2) || !strncasecmp(rule, "Accept(", 7)) { - m_eCommand = frAccept; - szRule += szRule[1] == ':' || szRule[1] == '(' ? 2 : 7; + m_command = frAccept; + rule += rule[1] == ':' || rule[1] == '(' ? 2 : 7; } - else if (!strncasecmp(szRule, "O(", 2) || !strncasecmp(szRule, "Options(", 8)) + else if (!strncasecmp(rule, "O(", 2) || !strncasecmp(rule, "Options(", 8)) { - m_eCommand = frOptions; - szRule += szRule[1] == ':' || szRule[1] == '(' ? 2 : 8; + m_command = frOptions; + rule += rule[1] == ':' || rule[1] == '(' ? 2 : 8; } - else if (!strncasecmp(szRule, "R:", 2) || !strncasecmp(szRule, "Reject:", 7)) + else if (!strncasecmp(rule, "R:", 2) || !strncasecmp(rule, "Reject:", 7)) { - m_eCommand = frReject; - szRule += szRule[1] == ':' || szRule[1] == '(' ? 2 : 7; + m_command = frReject; + rule += rule[1] == ':' || rule[1] == '(' ? 2 : 7; } - else if (!strncasecmp(szRule, "Q:", 2) || !strncasecmp(szRule, "Require:", 8)) + else if (!strncasecmp(rule, "Q:", 2) || !strncasecmp(rule, "Require:", 8)) { - m_eCommand = frRequire; - szRule += szRule[1] == ':' || szRule[1] == '(' ? 2 : 8; + m_command = frRequire; + rule += rule[1] == ':' || rule[1] == '(' ? 2 : 8; } - else if (*szRule == '#') + else if (*rule == '#') { - m_eCommand = frComment; - return szRule; + m_command = frComment; + return rule; } else { // not a command - return szRule; + return rule; } - if ((m_eCommand == frAccept || m_eCommand == frOptions) && szRule[-1] == '(') + if ((m_command == frAccept || m_command == frOptions) && rule[-1] == '(') { - szRule = CompileOptions(szRule); + rule = CompileOptions(rule); } - return szRule; + return rule; } -char* FeedFilter::Rule::CompileOptions(char* szRule) +char* FeedFilter::Rule::CompileOptions(char* rule) { - char* p = strchr(szRule, ')'); + char* p = strchr(rule, ')'); if (!p) { // error @@ -732,102 +732,102 @@ char* FeedFilter::Rule::CompileOptions(char* szRule) // split command into tokens *p = '\0'; - Tokenizer tok(szRule, ",", true); - while (char* szOption = tok.Next()) + Tokenizer tok(rule, ",", true); + while (char* option = tok.Next()) { - const char* szValue = ""; - char* szColon = strchr(szOption, ':'); - if (szColon) + const char* value = ""; + char* colon = strchr(option, ':'); + if (colon) { - *szColon = '\0'; - szValue = Util::Trim(szColon + 1); + *colon = '\0'; + value = Util::Trim(colon + 1); } - if (!strcasecmp(szOption, "category") || !strcasecmp(szOption, "cat") || !strcasecmp(szOption, "c")) + if (!strcasecmp(option, "category") || !strcasecmp(option, "cat") || !strcasecmp(option, "c")) { - m_bHasCategory = true; - free(m_szCategory); - m_szCategory = strdup(szValue); - m_bPatCategory = strstr(szValue, "${"); + m_hasCategory = true; + free(m_category); + m_category = strdup(value); + m_hasPatCategory = strstr(value, "${"); } - else if (!strcasecmp(szOption, "pause") || !strcasecmp(szOption, "p")) + else if (!strcasecmp(option, "pause") || !strcasecmp(option, "p")) { - m_bHasPause = true; - m_bPause = !*szValue || !strcasecmp(szValue, "yes") || !strcasecmp(szValue, "y"); - if (!m_bPause && !(!strcasecmp(szValue, "no") || !strcasecmp(szValue, "n"))) + m_hasPause = true; + m_pause = !*value || !strcasecmp(value, "yes") || !strcasecmp(value, "y"); + if (!m_pause && !(!strcasecmp(value, "no") || !strcasecmp(value, "n"))) { // error return NULL; } } - else if (!strcasecmp(szOption, "priority") || !strcasecmp(szOption, "pr") || !strcasecmp(szOption, "r")) + else if (!strcasecmp(option, "priority") || !strcasecmp(option, "pr") || !strcasecmp(option, "r")) { - if (!strchr("0123456789-+", *szValue)) + if (!strchr("0123456789-+", *value)) { // error return NULL; } - m_bHasPriority = true; - m_iPriority = atoi(szValue); + m_hasPriority = true; + m_priority = atoi(value); } - else if (!strcasecmp(szOption, "priority+") || !strcasecmp(szOption, "pr+") || !strcasecmp(szOption, "r+")) + else if (!strcasecmp(option, "priority+") || !strcasecmp(option, "pr+") || !strcasecmp(option, "r+")) { - if (!strchr("0123456789-+", *szValue)) + if (!strchr("0123456789-+", *value)) { // error return NULL; } - m_bHasAddPriority = true; - m_iAddPriority = atoi(szValue); + m_hasAddPriority = true; + m_addPriority = atoi(value); } - else if (!strcasecmp(szOption, "dupescore") || !strcasecmp(szOption, "ds") || !strcasecmp(szOption, "s")) + else if (!strcasecmp(option, "dupescore") || !strcasecmp(option, "ds") || !strcasecmp(option, "s")) { - if (!strchr("0123456789-+", *szValue)) + if (!strchr("0123456789-+", *value)) { // error return NULL; } - m_bHasDupeScore = true; - m_iDupeScore = atoi(szValue); + m_hasDupeScore = true; + m_dupeScore = atoi(value); } - else if (!strcasecmp(szOption, "dupescore+") || !strcasecmp(szOption, "ds+") || !strcasecmp(szOption, "s+")) + else if (!strcasecmp(option, "dupescore+") || !strcasecmp(option, "ds+") || !strcasecmp(option, "s+")) { - if (!strchr("0123456789-+", *szValue)) + if (!strchr("0123456789-+", *value)) { // error return NULL; } - m_bHasAddDupeScore = true; - m_iAddDupeScore = atoi(szValue); + m_hasAddDupeScore = true; + m_addDupeScore = atoi(value); } - else if (!strcasecmp(szOption, "dupekey") || !strcasecmp(szOption, "dk") || !strcasecmp(szOption, "k")) + else if (!strcasecmp(option, "dupekey") || !strcasecmp(option, "dk") || !strcasecmp(option, "k")) { - m_bHasDupeKey = true; - free(m_szDupeKey); - m_szDupeKey = strdup(szValue); - m_bPatDupeKey = strstr(szValue, "${"); + m_hasDupeKey = true; + free(m_dupeKey); + m_dupeKey = strdup(value); + m_hasPatDupeKey = strstr(value, "${"); } - else if (!strcasecmp(szOption, "dupekey+") || !strcasecmp(szOption, "dk+") || !strcasecmp(szOption, "k+")) + else if (!strcasecmp(option, "dupekey+") || !strcasecmp(option, "dk+") || !strcasecmp(option, "k+")) { - m_bHasAddDupeKey = true; - free(m_szAddDupeKey); - m_szAddDupeKey = strdup(szValue); - m_bPatAddDupeKey = strstr(szValue, "${"); + m_hasAddDupeKey = true; + free(m_addDupeKey); + m_addDupeKey = strdup(value); + m_hasPatAddDupeKey = strstr(value, "${"); } - else if (!strcasecmp(szOption, "dupemode") || !strcasecmp(szOption, "dm") || !strcasecmp(szOption, "m")) + else if (!strcasecmp(option, "dupemode") || !strcasecmp(option, "dm") || !strcasecmp(option, "m")) { - m_bHasDupeMode = true; - if (!strcasecmp(szValue, "score") || !strcasecmp(szValue, "s")) + m_hasDupeMode = true; + if (!strcasecmp(value, "score") || !strcasecmp(value, "s")) { - m_eDupeMode = dmScore; + m_dupeMode = dmScore; } - else if (!strcasecmp(szValue, "all") || !strcasecmp(szValue, "a")) + else if (!strcasecmp(value, "all") || !strcasecmp(value, "a")) { - m_eDupeMode = dmAll; + m_dupeMode = dmAll; } - else if (!strcasecmp(szValue, "force") || !strcasecmp(szValue, "f")) + else if (!strcasecmp(value, "force") || !strcasecmp(value, "f")) { - m_eDupeMode = dmForce; + m_dupeMode = dmForce; } else { @@ -835,101 +835,101 @@ char* FeedFilter::Rule::CompileOptions(char* szRule) return NULL; } } - else if (!strcasecmp(szOption, "rageid")) + else if (!strcasecmp(option, "rageid")) { - m_bHasRageId = true; - free(m_szRageId); - m_szRageId = strdup(szValue); + m_hasRageId = true; + free(m_rageId); + m_rageId = strdup(value); } - else if (!strcasecmp(szOption, "series")) + else if (!strcasecmp(option, "series")) { - m_bHasSeries = true; - free(m_szSeries); - m_szSeries = strdup(szValue); + m_hasSeries = true; + free(m_series); + m_series = strdup(value); } // for compatibility with older version we support old commands too - else if (!strcasecmp(szOption, "paused") || !strcasecmp(szOption, "unpaused")) + else if (!strcasecmp(option, "paused") || !strcasecmp(option, "unpaused")) { - m_bHasPause = true; - m_bPause = !strcasecmp(szOption, "paused"); + m_hasPause = true; + m_pause = !strcasecmp(option, "paused"); } - else if (strchr("0123456789-+", *szOption)) + else if (strchr("0123456789-+", *option)) { - m_bHasPriority = true; - m_iPriority = atoi(szOption); + m_hasPriority = true; + m_priority = atoi(option); } else { - m_bHasCategory = true; - free(m_szCategory); - m_szCategory = strdup(szOption); + m_hasCategory = true; + free(m_category); + m_category = strdup(option); } } - szRule = p + 1; - if (*szRule == ':') + rule = p + 1; + if (*rule == ':') { - szRule++; + rule++; } - return szRule; + return rule; } -bool FeedFilter::Rule::CompileTerm(char* szTerm) +bool FeedFilter::Rule::CompileTerm(char* termstr) { - Term* pTerm = new Term(); - pTerm->SetRefValues(m_bPatCategory || m_bPatDupeKey || m_bPatAddDupeKey ? &m_RefValues : NULL); - if (pTerm->Compile(szTerm)) + Term* term = new Term(); + term->SetRefValues(m_hasPatCategory || m_hasPatDupeKey || m_hasPatAddDupeKey ? &m_refValues : NULL); + if (term->Compile(termstr)) { - m_Terms.push_back(pTerm); + m_terms.push_back(term); return true; } else { - delete pTerm; + delete term; return false; } } -bool FeedFilter::Rule::Match(FeedItemInfo* pFeedItemInfo) +bool FeedFilter::Rule::Match(FeedItemInfo* feedItemInfo) { - for (RefValues::iterator it = m_RefValues.begin(); it != m_RefValues.end(); it++) + for (RefValues::iterator it = m_refValues.begin(); it != m_refValues.end(); it++) { delete *it; } - m_RefValues.clear(); + m_refValues.clear(); - if (!MatchExpression(pFeedItemInfo)) + if (!MatchExpression(feedItemInfo)) { return false; } - if (m_bPatCategory) + if (m_hasPatCategory) { - ExpandRefValues(pFeedItemInfo, &m_szCategory, m_szPatCategory); + ExpandRefValues(feedItemInfo, &m_category, m_patCategory); } - if (m_bPatDupeKey) + if (m_hasPatDupeKey) { - ExpandRefValues(pFeedItemInfo, &m_szDupeKey, m_szPatDupeKey); + ExpandRefValues(feedItemInfo, &m_dupeKey, m_patDupeKey); } - if (m_bPatAddDupeKey) + if (m_hasPatAddDupeKey) { - ExpandRefValues(pFeedItemInfo, &m_szAddDupeKey, m_szPatAddDupeKey); + ExpandRefValues(feedItemInfo, &m_addDupeKey, m_patAddDupeKey); } return true; } -bool FeedFilter::Rule::MatchExpression(FeedItemInfo* pFeedItemInfo) +bool FeedFilter::Rule::MatchExpression(FeedItemInfo* feedItemInfo) { - char* expr = (char*)malloc(m_Terms.size() + 1); + char* expr = (char*)malloc(m_terms.size() + 1); int index = 0; - for (TermList::iterator it = m_Terms.begin(); it != m_Terms.end(); it++, index++) + for (TermList::iterator it = m_terms.begin(); it != m_terms.end(); it++, index++) { - Term* pTerm = *it; - switch (pTerm->GetCommand()) + Term* term = *it; + switch (term->GetCommand()) { case fcOpeningBrace: expr[index] = '('; @@ -944,14 +944,14 @@ bool FeedFilter::Rule::MatchExpression(FeedItemInfo* pFeedItemInfo) break; default: - expr[index] = pTerm->Match(pFeedItemInfo) ? 'T' : 'F'; + expr[index] = term->Match(feedItemInfo) ? 'T' : 'F'; break; } } expr[index] = '\0'; // reduce result tree to one element (may be longer if expression has syntax errors) - for (int iOldLen = 0, iNewLen = strlen(expr); iNewLen != iOldLen; iOldLen = iNewLen, iNewLen = strlen(expr)) + for (int oldLen = 0, newLen = strlen(expr); newLen != oldLen; oldLen = newLen, newLen = strlen(expr)) { // NOTE: there are no operator priorities. // the order of operators "OR" and "AND" is not defined, they can be checked in any order. @@ -971,23 +971,23 @@ bool FeedFilter::Rule::MatchExpression(FeedItemInfo* pFeedItemInfo) Util::ReduceStr(expr, "(F)", "F"); } - bool bMatch = *expr && *expr == 'T' && expr[1] == '\0'; + bool match = *expr && *expr == 'T' && expr[1] == '\0'; free(expr); - return bMatch; + return match; } -void FeedFilter::Rule::ExpandRefValues(FeedItemInfo* pFeedItemInfo, char** pDestStr, char* pPatStr) +void FeedFilter::Rule::ExpandRefValues(FeedItemInfo* feedItemInfo, char** destStr, char* patStr) { - free(*pDestStr); + free(*destStr); - *pDestStr = strdup(pPatStr); - char* curvalue = *pDestStr; + *destStr = strdup(patStr); + char* curvalue = *destStr; - int iAttempts = 0; + int attempts = 0; while (char* dollar = strstr(curvalue, "${")) { - iAttempts++; - if (iAttempts > 100) + attempts++; + if (attempts > 100) { break; // error } @@ -1004,7 +1004,7 @@ void FeedFilter::Rule::ExpandRefValues(FeedItemInfo* pFeedItemInfo, char** pDest strncpy(variable, dollar + 2, maxlen); variable[maxlen] = '\0'; - const char* varvalue = GetRefValue(pFeedItemInfo, variable); + const char* varvalue = GetRefValue(feedItemInfo, variable); if (!varvalue) { break; // error @@ -1017,95 +1017,95 @@ void FeedFilter::Rule::ExpandRefValues(FeedItemInfo* pFeedItemInfo, char** pDest strcpy(newvalue + (dollar - curvalue) + newlen, end + 1); free(curvalue); curvalue = newvalue; - *pDestStr = curvalue; + *destStr = curvalue; } } -const char* FeedFilter::Rule::GetRefValue(FeedItemInfo* pFeedItemInfo, const char* szVarName) +const char* FeedFilter::Rule::GetRefValue(FeedItemInfo* feedItemInfo, const char* varName) { - if (!strcasecmp(szVarName, "season")) + if (!strcasecmp(varName, "season")) { - pFeedItemInfo->GetSeasonNum(); // needed to parse title - return pFeedItemInfo->GetSeason() ? pFeedItemInfo->GetSeason() : ""; + feedItemInfo->GetSeasonNum(); // needed to parse title + return feedItemInfo->GetSeason() ? feedItemInfo->GetSeason() : ""; } - else if (!strcasecmp(szVarName, "episode")) + else if (!strcasecmp(varName, "episode")) { - pFeedItemInfo->GetEpisodeNum(); // needed to parse title - return pFeedItemInfo->GetEpisode() ? pFeedItemInfo->GetEpisode() : ""; + feedItemInfo->GetEpisodeNum(); // needed to parse title + return feedItemInfo->GetEpisode() ? feedItemInfo->GetEpisode() : ""; } - int iIndex = atoi(szVarName) - 1; - if (iIndex >= 0 && iIndex < (int)m_RefValues.size()) + int index = atoi(varName) - 1; + if (index >= 0 && index < (int)m_refValues.size()) { - return m_RefValues[iIndex]; + return m_refValues[index]; } return NULL; } -FeedFilter::FeedFilter(const char* szFilter) +FeedFilter::FeedFilter(const char* filter) { - Compile(szFilter); + Compile(filter); } FeedFilter::~FeedFilter() { - for (RuleList::iterator it = m_Rules.begin(); it != m_Rules.end(); it++) + for (RuleList::iterator it = m_rules.begin(); it != m_rules.end(); it++) { delete *it; } } -void FeedFilter::Compile(const char* szFilter) +void FeedFilter::Compile(const char* filter) { - debug("Compiling filter: %s", szFilter); + debug("Compiling filter: %s", filter); - char* szFilter2 = strdup(szFilter); - char* szRule = szFilter2; + char* filter2 = strdup(filter); + char* rule = filter2; - for (char* p = szRule; *p; p++) + for (char* p = rule; *p; p++) { char ch = *p; if (ch == '%') { *p = '\0'; - CompileRule(szRule); - szRule = p + 1; + CompileRule(rule); + rule = p + 1; } } - CompileRule(szRule); + CompileRule(rule); - free(szFilter2); + free(filter2); } -void FeedFilter::CompileRule(char* szRule) +void FeedFilter::CompileRule(char* rulestr) { - Rule* pRule = new Rule(); - m_Rules.push_back(pRule); - pRule->Compile(szRule); + Rule* rule = new Rule(); + m_rules.push_back(rule); + rule->Compile(rulestr); } -void FeedFilter::Match(FeedItemInfo* pFeedItemInfo) +void FeedFilter::Match(FeedItemInfo* feedItemInfo) { int index = 0; - for (RuleList::iterator it = m_Rules.begin(); it != m_Rules.end(); it++) + for (RuleList::iterator it = m_rules.begin(); it != m_rules.end(); it++) { - Rule* pRule = *it; + Rule* rule = *it; index++; - if (pRule->IsValid()) + if (rule->IsValid()) { - bool bMatch = pRule->Match(pFeedItemInfo); - switch (pRule->GetCommand()) + bool match = rule->Match(feedItemInfo); + switch (rule->GetCommand()) { case frAccept: case frOptions: - if (bMatch) + if (match) { - pFeedItemInfo->SetMatchStatus(FeedItemInfo::msAccepted); - pFeedItemInfo->SetMatchRule(index); - ApplyOptions(pRule, pFeedItemInfo); - if (pRule->GetCommand() == frAccept) + feedItemInfo->SetMatchStatus(FeedItemInfo::msAccepted); + feedItemInfo->SetMatchRule(index); + ApplyOptions(rule, feedItemInfo); + if (rule->GetCommand() == frAccept) { return; } @@ -1113,19 +1113,19 @@ void FeedFilter::Match(FeedItemInfo* pFeedItemInfo) break; case frReject: - if (bMatch) + if (match) { - pFeedItemInfo->SetMatchStatus(FeedItemInfo::msRejected); - pFeedItemInfo->SetMatchRule(index); + feedItemInfo->SetMatchStatus(FeedItemInfo::msRejected); + feedItemInfo->SetMatchRule(index); return; } break; case frRequire: - if (!bMatch) + if (!match) { - pFeedItemInfo->SetMatchStatus(FeedItemInfo::msRejected); - pFeedItemInfo->SetMatchRule(index); + feedItemInfo->SetMatchStatus(FeedItemInfo::msRejected); + feedItemInfo->SetMatchRule(index); return; } break; @@ -1136,50 +1136,50 @@ void FeedFilter::Match(FeedItemInfo* pFeedItemInfo) } } - pFeedItemInfo->SetMatchStatus(FeedItemInfo::msIgnored); - pFeedItemInfo->SetMatchRule(0); + feedItemInfo->SetMatchStatus(FeedItemInfo::msIgnored); + feedItemInfo->SetMatchRule(0); } -void FeedFilter::ApplyOptions(Rule* pRule, FeedItemInfo* pFeedItemInfo) +void FeedFilter::ApplyOptions(Rule* rule, FeedItemInfo* feedItemInfo) { - if (pRule->HasPause()) + if (rule->HasPause()) { - pFeedItemInfo->SetPauseNzb(pRule->GetPause()); + feedItemInfo->SetPauseNzb(rule->GetPause()); } - if (pRule->HasCategory()) + if (rule->HasCategory()) { - pFeedItemInfo->SetAddCategory(pRule->GetCategory()); + feedItemInfo->SetAddCategory(rule->GetCategory()); } - if (pRule->HasPriority()) + if (rule->HasPriority()) { - pFeedItemInfo->SetPriority(pRule->GetPriority()); + feedItemInfo->SetPriority(rule->GetPriority()); } - if (pRule->HasAddPriority()) + if (rule->HasAddPriority()) { - pFeedItemInfo->SetPriority(pFeedItemInfo->GetPriority() + pRule->GetAddPriority()); + feedItemInfo->SetPriority(feedItemInfo->GetPriority() + rule->GetAddPriority()); } - if (pRule->HasDupeScore()) + if (rule->HasDupeScore()) { - pFeedItemInfo->SetDupeScore(pRule->GetDupeScore()); + feedItemInfo->SetDupeScore(rule->GetDupeScore()); } - if (pRule->HasAddDupeScore()) + if (rule->HasAddDupeScore()) { - pFeedItemInfo->SetDupeScore(pFeedItemInfo->GetDupeScore() + pRule->GetAddDupeScore()); + feedItemInfo->SetDupeScore(feedItemInfo->GetDupeScore() + rule->GetAddDupeScore()); } - if (pRule->HasRageId() || pRule->HasSeries()) + if (rule->HasRageId() || rule->HasSeries()) { - pFeedItemInfo->BuildDupeKey(pRule->GetRageId(), pRule->GetSeries()); + feedItemInfo->BuildDupeKey(rule->GetRageId(), rule->GetSeries()); } - if (pRule->HasDupeKey()) + if (rule->HasDupeKey()) { - pFeedItemInfo->SetDupeKey(pRule->GetDupeKey()); + feedItemInfo->SetDupeKey(rule->GetDupeKey()); } - if (pRule->HasAddDupeKey()) + if (rule->HasAddDupeKey()) { - pFeedItemInfo->AppendDupeKey(pRule->GetAddDupeKey()); + feedItemInfo->AppendDupeKey(rule->GetAddDupeKey()); } - if (pRule->HasDupeMode()) + if (rule->HasDupeMode()) { - pFeedItemInfo->SetDupeMode(pRule->GetDupeMode()); + feedItemInfo->SetDupeMode(rule->GetDupeMode()); } } diff --git a/daemon/feed/FeedFilter.h b/daemon/feed/FeedFilter.h index 15dad69a..4c54caff 100644 --- a/daemon/feed/FeedFilter.h +++ b/daemon/feed/FeedFilter.h @@ -52,35 +52,35 @@ private: class Term { private: - bool m_bPositive; - char* m_szField; - ETermCommand m_eCommand; - char* m_szParam; - long long m_iIntParam; + bool m_positive; + char* m_field; + ETermCommand m_command; + char* m_param; + long long m_intParam; double m_fFloatParam; - bool m_bFloat; - RegEx* m_pRegEx; - RefValues* m_pRefValues; + bool m_float; + RegEx* m_regEx; + RefValues* m_refValues; - bool GetFieldData(const char* szField, FeedItemInfo* pFeedItemInfo, + bool GetFieldData(const char* field, FeedItemInfo* feedItemInfo, const char** StrValue, long long* IntValue); - bool ParseParam(const char* szField, const char* szParam); - bool ParseSizeParam(const char* szParam); - bool ParseAgeParam(const char* szParam); - bool ParseNumericParam(const char* szParam); - bool MatchValue(const char* szStrValue, long long iIntValue); - bool MatchText(const char* szStrValue); - bool MatchRegex(const char* szStrValue); - void FillWildMaskRefValues(const char* szStrValue, WildMask* pMask, int iRefOffset); - void FillRegExRefValues(const char* szStrValue, RegEx* pRegEx); + bool ParseParam(const char* field, const char* param); + bool ParseSizeParam(const char* param); + bool ParseAgeParam(const char* param); + bool ParseNumericParam(const char* param); + bool MatchValue(const char* strValue, long long intValue); + bool MatchText(const char* strValue); + bool MatchRegex(const char* strValue); + void FillWildMaskRefValues(const char* strValue, WildMask* mask, int refOffset); + void FillRegExRefValues(const char* strValue, RegEx* regEx); public: Term(); ~Term(); - void SetRefValues(RefValues* pRefValues) { m_pRefValues = pRefValues; } - bool Compile(char* szToken); - bool Match(FeedItemInfo* pFeedItemInfo); - ETermCommand GetCommand() { return m_eCommand; } + void SetRefValues(RefValues* refValues) { m_refValues = refValues; } + bool Compile(char* token); + bool Match(FeedItemInfo* feedItemInfo); + ETermCommand GetCommand() { return m_command; } }; typedef std::deque TermList; @@ -97,90 +97,90 @@ private: class Rule { private: - bool m_bIsValid; - ERuleCommand m_eCommand; - char* m_szCategory; - int m_iPriority; - int m_iAddPriority; - bool m_bPause; - int m_iDupeScore; - int m_iAddDupeScore; - char* m_szDupeKey; - char* m_szAddDupeKey; - EDupeMode m_eDupeMode; - char* m_szSeries; - char* m_szRageId; - bool m_bHasCategory; - bool m_bHasPriority; - bool m_bHasAddPriority; - bool m_bHasPause; - bool m_bHasDupeScore; - bool m_bHasAddDupeScore; - bool m_bHasDupeKey; - bool m_bHasAddDupeKey; - bool m_bHasDupeMode; - bool m_bPatCategory; - bool m_bPatDupeKey; - bool m_bPatAddDupeKey; - bool m_bHasSeries; - bool m_bHasRageId; - char* m_szPatCategory; - char* m_szPatDupeKey; - char* m_szPatAddDupeKey; - TermList m_Terms; - RefValues m_RefValues; + bool m_isValid; + ERuleCommand m_command; + char* m_category; + int m_priority; + int m_addPriority; + bool m_pause; + int m_dupeScore; + int m_addDupeScore; + char* m_dupeKey; + char* m_addDupeKey; + EDupeMode m_dupeMode; + char* m_series; + char* m_rageId; + bool m_hasCategory; + bool m_hasPriority; + bool m_hasAddPriority; + bool m_hasPause; + bool m_hasDupeScore; + bool m_hasAddDupeScore; + bool m_hasDupeKey; + bool m_hasAddDupeKey; + bool m_hasDupeMode; + bool m_hasPatCategory; + bool m_hasPatDupeKey; + bool m_hasPatAddDupeKey; + bool m_hasSeries; + bool m_hasRageId; + char* m_patCategory; + char* m_patDupeKey; + char* m_patAddDupeKey; + TermList m_terms; + RefValues m_refValues; - char* CompileCommand(char* szRule); - char* CompileOptions(char* szRule); - bool CompileTerm(char* szTerm); - bool MatchExpression(FeedItemInfo* pFeedItemInfo); + char* CompileCommand(char* rule); + char* CompileOptions(char* rule); + bool CompileTerm(char* term); + bool MatchExpression(FeedItemInfo* feedItemInfo); public: Rule(); ~Rule(); - void Compile(char* szRule); - bool IsValid() { return m_bIsValid; } - ERuleCommand GetCommand() { return m_eCommand; } - const char* GetCategory() { return m_szCategory; } - int GetPriority() { return m_iPriority; } - int GetAddPriority() { return m_iAddPriority; } - bool GetPause() { return m_bPause; } - const char* GetDupeKey() { return m_szDupeKey; } - const char* GetAddDupeKey() { return m_szAddDupeKey; } - int GetDupeScore() { return m_iDupeScore; } - int GetAddDupeScore() { return m_iAddDupeScore; } - EDupeMode GetDupeMode() { return m_eDupeMode; } - const char* GetRageId() { return m_szRageId; } - const char* GetSeries() { return m_szSeries; } - bool HasCategory() { return m_bHasCategory; } - bool HasPriority() { return m_bHasPriority; } - bool HasAddPriority() { return m_bHasAddPriority; } - bool HasPause() { return m_bHasPause; } - bool HasDupeScore() { return m_bHasDupeScore; } - bool HasAddDupeScore() { return m_bHasAddDupeScore; } - bool HasDupeKey() { return m_bHasDupeKey; } - bool HasAddDupeKey() { return m_bHasAddDupeKey; } - bool HasDupeMode() { return m_bHasDupeMode; } - bool HasRageId() { return m_bHasRageId; } - bool HasSeries() { return m_bHasSeries; } - bool Match(FeedItemInfo* pFeedItemInfo); - void ExpandRefValues(FeedItemInfo* pFeedItemInfo, char** pDestStr, char* pPatStr); - const char* GetRefValue(FeedItemInfo* pFeedItemInfo, const char* szVarName); + void Compile(char* rule); + bool IsValid() { return m_isValid; } + ERuleCommand GetCommand() { return m_command; } + const char* GetCategory() { return m_category; } + int GetPriority() { return m_priority; } + int GetAddPriority() { return m_addPriority; } + bool GetPause() { return m_pause; } + const char* GetDupeKey() { return m_dupeKey; } + const char* GetAddDupeKey() { return m_addDupeKey; } + int GetDupeScore() { return m_dupeScore; } + int GetAddDupeScore() { return m_addDupeScore; } + EDupeMode GetDupeMode() { return m_dupeMode; } + const char* GetRageId() { return m_rageId; } + const char* GetSeries() { return m_series; } + bool HasCategory() { return m_hasCategory; } + bool HasPriority() { return m_hasPriority; } + bool HasAddPriority() { return m_hasAddPriority; } + bool HasPause() { return m_hasPause; } + bool HasDupeScore() { return m_hasDupeScore; } + bool HasAddDupeScore() { return m_hasAddDupeScore; } + bool HasDupeKey() { return m_hasDupeKey; } + bool HasAddDupeKey() { return m_hasAddDupeKey; } + bool HasDupeMode() { return m_hasDupeMode; } + bool HasRageId() { return m_hasRageId; } + bool HasSeries() { return m_hasSeries; } + bool Match(FeedItemInfo* feedItemInfo); + void ExpandRefValues(FeedItemInfo* feedItemInfo, char** destStr, char* patStr); + const char* GetRefValue(FeedItemInfo* feedItemInfo, const char* varName); }; typedef std::deque RuleList; private: - RuleList m_Rules; + RuleList m_rules; - void Compile(const char* szFilter); - void CompileRule(char* szRule); - void ApplyOptions(Rule* pRule, FeedItemInfo* pFeedItemInfo); + void Compile(const char* filter); + void CompileRule(char* rule); + void ApplyOptions(Rule* rule, FeedItemInfo* feedItemInfo); public: - FeedFilter(const char* szFilter); + FeedFilter(const char* filter); ~FeedFilter(); - void Match(FeedItemInfo* pFeedItemInfo); + void Match(FeedItemInfo* feedItemInfo); }; #endif diff --git a/daemon/feed/FeedInfo.cpp b/daemon/feed/FeedInfo.cpp index 4e2fbb8c..43094a44 100644 --- a/daemon/feed/FeedInfo.cpp +++ b/daemon/feed/FeedInfo.cpp @@ -41,55 +41,55 @@ #include "FeedInfo.h" #include "Util.h" -FeedInfo::FeedInfo(int iID, const char* szName, const char* szUrl, bool bBacklog, int iInterval, - const char* szFilter, bool bPauseNzb, const char* szCategory, int iPriority, const char* szFeedScript) +FeedInfo::FeedInfo(int id, const char* name, const char* url, bool backlog, int interval, + const char* filter, bool pauseNzb, const char* category, int priority, const char* feedScript) { - m_iID = iID; - m_szName = strdup(szName ? szName : ""); - m_szUrl = strdup(szUrl ? szUrl : ""); - m_szFilter = strdup(szFilter ? szFilter : ""); - m_bBacklog = bBacklog; - m_iFilterHash = Util::HashBJ96(m_szFilter, strlen(m_szFilter), 0); - m_szCategory = strdup(szCategory ? szCategory : ""); - m_iInterval = iInterval; - m_szFeedScript = strdup(szFeedScript ? szFeedScript : ""); - m_bPauseNzb = bPauseNzb; - m_iPriority = iPriority; - m_tLastUpdate = 0; - m_bPreview = false; - m_eStatus = fsUndefined; - m_szOutputFilename = NULL; - m_bFetch = false; - m_bForce = false; + m_id = id; + m_name = strdup(name ? name : ""); + m_url = strdup(url ? url : ""); + m_filter = strdup(filter ? filter : ""); + m_backlog = backlog; + m_filterHash = Util::HashBJ96(m_filter, strlen(m_filter), 0); + m_category = strdup(category ? category : ""); + m_interval = interval; + m_feedScript = strdup(feedScript ? feedScript : ""); + m_pauseNzb = pauseNzb; + m_priority = priority; + m_lastUpdate = 0; + m_preview = false; + m_status = fsUndefined; + m_outputFilename = NULL; + m_fetch = false; + m_force = false; } FeedInfo::~FeedInfo() { - free(m_szName); - free(m_szUrl); - free(m_szFilter); - free(m_szCategory); - free(m_szOutputFilename); - free(m_szFeedScript); + free(m_name); + free(m_url); + free(m_filter); + free(m_category); + free(m_outputFilename); + free(m_feedScript); } -void FeedInfo::SetOutputFilename(const char* szOutputFilename) +void FeedInfo::SetOutputFilename(const char* outputFilename) { - free(m_szOutputFilename); - m_szOutputFilename = strdup(szOutputFilename); + free(m_outputFilename); + m_outputFilename = strdup(outputFilename); } -FeedItemInfo::Attr::Attr(const char* szName, const char* szValue) +FeedItemInfo::Attr::Attr(const char* name, const char* value) { - m_szName = strdup(szName ? szName : ""); - m_szValue = strdup(szValue ? szValue : ""); + m_name = strdup(name ? name : ""); + m_value = strdup(value ? value : ""); } FeedItemInfo::Attr::~Attr() { - free(m_szName); - free(m_szValue); + free(m_name); + free(m_value); } @@ -101,19 +101,19 @@ FeedItemInfo::Attributes::~Attributes() } } -void FeedItemInfo::Attributes::Add(const char* szName, const char* szValue) +void FeedItemInfo::Attributes::Add(const char* name, const char* value) { - push_back(new Attr(szName, szValue)); + push_back(new Attr(name, value)); } -FeedItemInfo::Attr* FeedItemInfo::Attributes::Find(const char* szName) +FeedItemInfo::Attr* FeedItemInfo::Attributes::Find(const char* name) { for (iterator it = begin(); it != end(); it++) { - Attr* pAttr = *it; - if (!strcasecmp(pAttr->GetName(), szName)) + Attr* attr = *it; + if (!strcasecmp(attr->GetName(), name)) { - return pAttr; + return attr; } } @@ -123,234 +123,234 @@ FeedItemInfo::Attr* FeedItemInfo::Attributes::Find(const char* szName) FeedItemInfo::FeedItemInfo() { - m_pFeedFilterHelper = NULL; - m_szTitle = NULL; - m_szFilename = NULL; - m_szUrl = NULL; - m_szCategory = strdup(""); - m_lSize = 0; - m_tTime = 0; - m_iImdbId = 0; - m_iRageId = 0; - m_szDescription = strdup(""); - m_szSeason = NULL; - m_szEpisode = NULL; - m_iSeasonNum = 0; - m_iEpisodeNum = 0; - m_bSeasonEpisodeParsed = false; - m_szAddCategory = strdup(""); - m_bPauseNzb = false; - m_iPriority = 0; - m_eStatus = isUnknown; - m_eMatchStatus = msIgnored; - m_iMatchRule = 0; - m_szDupeKey = NULL; - m_iDupeScore = 0; - m_eDupeMode = dmScore; - m_szDupeStatus = NULL; + m_feedFilterHelper = NULL; + m_title = NULL; + m_filename = NULL; + m_url = NULL; + m_category = strdup(""); + m_size = 0; + m_time = 0; + m_imdbId = 0; + m_rageId = 0; + m_description = strdup(""); + m_season = NULL; + m_episode = NULL; + m_seasonNum = 0; + m_episodeNum = 0; + m_seasonEpisodeParsed = false; + m_addCategory = strdup(""); + m_pauseNzb = false; + m_priority = 0; + m_status = isUnknown; + m_matchStatus = msIgnored; + m_matchRule = 0; + m_dupeKey = NULL; + m_dupeScore = 0; + m_dupeMode = dmScore; + m_dupeStatus = NULL; } FeedItemInfo::~FeedItemInfo() { - free(m_szTitle); - free(m_szFilename); - free(m_szUrl); - free(m_szCategory); - free(m_szDescription); - free(m_szSeason); - free(m_szEpisode); - free(m_szAddCategory); - free(m_szDupeKey); - free(m_szDupeStatus); + free(m_title); + free(m_filename); + free(m_url); + free(m_category); + free(m_description); + free(m_season); + free(m_episode); + free(m_addCategory); + free(m_dupeKey); + free(m_dupeStatus); } -void FeedItemInfo::SetTitle(const char* szTitle) +void FeedItemInfo::SetTitle(const char* title) { - free(m_szTitle); - m_szTitle = szTitle ? strdup(szTitle) : NULL; + free(m_title); + m_title = title ? strdup(title) : NULL; } -void FeedItemInfo::SetFilename(const char* szFilename) +void FeedItemInfo::SetFilename(const char* filename) { - free(m_szFilename); - m_szFilename = szFilename ? strdup(szFilename) : NULL; + free(m_filename); + m_filename = filename ? strdup(filename) : NULL; } -void FeedItemInfo::SetUrl(const char* szUrl) +void FeedItemInfo::SetUrl(const char* url) { - free(m_szUrl); - m_szUrl = szUrl ? strdup(szUrl) : NULL; + free(m_url); + m_url = url ? strdup(url) : NULL; } -void FeedItemInfo::SetCategory(const char* szCategory) +void FeedItemInfo::SetCategory(const char* category) { - free(m_szCategory); - m_szCategory = strdup(szCategory ? szCategory: ""); + free(m_category); + m_category = strdup(category ? category: ""); } -void FeedItemInfo::SetDescription(const char* szDescription) +void FeedItemInfo::SetDescription(const char* description) { - free(m_szDescription); - m_szDescription = strdup(szDescription ? szDescription: ""); + free(m_description); + m_description = strdup(description ? description: ""); } -void FeedItemInfo::SetSeason(const char* szSeason) +void FeedItemInfo::SetSeason(const char* season) { - free(m_szSeason); - m_szSeason = szSeason ? strdup(szSeason) : NULL; - m_iSeasonNum = szSeason ? ParsePrefixedInt(szSeason) : 0; + free(m_season); + m_season = season ? strdup(season) : NULL; + m_seasonNum = season ? ParsePrefixedInt(season) : 0; } -void FeedItemInfo::SetEpisode(const char* szEpisode) +void FeedItemInfo::SetEpisode(const char* episode) { - free(m_szEpisode); - m_szEpisode = szEpisode ? strdup(szEpisode) : NULL; - m_iEpisodeNum = szEpisode ? ParsePrefixedInt(szEpisode) : 0; + free(m_episode); + m_episode = episode ? strdup(episode) : NULL; + m_episodeNum = episode ? ParsePrefixedInt(episode) : 0; } -int FeedItemInfo::ParsePrefixedInt(const char *szValue) +int FeedItemInfo::ParsePrefixedInt(const char *value) { - const char* szVal = szValue; - if (!strchr("0123456789", *szVal)) + const char* val = value; + if (!strchr("0123456789", *val)) { - szVal++; + val++; } - return atoi(szVal); + return atoi(val); } -void FeedItemInfo::SetAddCategory(const char* szAddCategory) +void FeedItemInfo::SetAddCategory(const char* addCategory) { - free(m_szAddCategory); - m_szAddCategory = strdup(szAddCategory ? szAddCategory : ""); + free(m_addCategory); + m_addCategory = strdup(addCategory ? addCategory : ""); } -void FeedItemInfo::SetDupeKey(const char* szDupeKey) +void FeedItemInfo::SetDupeKey(const char* dupeKey) { - free(m_szDupeKey); - m_szDupeKey = strdup(szDupeKey ? szDupeKey : ""); + free(m_dupeKey); + m_dupeKey = strdup(dupeKey ? dupeKey : ""); } -void FeedItemInfo::AppendDupeKey(const char* szExtraDupeKey) +void FeedItemInfo::AppendDupeKey(const char* extraDupeKey) { - if (!m_szDupeKey || *m_szDupeKey == '\0' || !szExtraDupeKey || *szExtraDupeKey == '\0') + if (!m_dupeKey || *m_dupeKey == '\0' || !extraDupeKey || *extraDupeKey == '\0') { return; } - int iLen = (m_szDupeKey ? strlen(m_szDupeKey) : 0) + 1 + strlen(szExtraDupeKey) + 1; - char* szNewKey = (char*)malloc(iLen); - snprintf(szNewKey, iLen, "%s-%s", m_szDupeKey, szExtraDupeKey); - szNewKey[iLen - 1] = '\0'; + int len = (m_dupeKey ? strlen(m_dupeKey) : 0) + 1 + strlen(extraDupeKey) + 1; + char* newKey = (char*)malloc(len); + snprintf(newKey, len, "%s-%s", m_dupeKey, extraDupeKey); + newKey[len - 1] = '\0'; - free(m_szDupeKey); - m_szDupeKey = szNewKey; + free(m_dupeKey); + m_dupeKey = newKey; } -void FeedItemInfo::BuildDupeKey(const char* szRageId, const char* szSeries) +void FeedItemInfo::BuildDupeKey(const char* rageId, const char* series) { - int iRageId = szRageId && *szRageId ? atoi(szRageId) : m_iRageId; + int rageIdVal = rageId && *rageId ? atoi(rageId) : m_rageId; - free(m_szDupeKey); + free(m_dupeKey); - if (m_iImdbId != 0) + if (m_imdbId != 0) { - m_szDupeKey = (char*)malloc(20); - snprintf(m_szDupeKey, 20, "imdb=%i", m_iImdbId); + m_dupeKey = (char*)malloc(20); + snprintf(m_dupeKey, 20, "imdb=%i", m_imdbId); } - else if (szSeries && *szSeries && GetSeasonNum() != 0 && GetEpisodeNum() != 0) + else if (series && *series && GetSeasonNum() != 0 && GetEpisodeNum() != 0) { - int iLen = strlen(szSeries) + 50; - m_szDupeKey = (char*)malloc(iLen); - snprintf(m_szDupeKey, iLen, "series=%s-%s-%s", szSeries, m_szSeason, m_szEpisode); - m_szDupeKey[iLen-1] = '\0'; + int len = strlen(series) + 50; + m_dupeKey = (char*)malloc(len); + snprintf(m_dupeKey, len, "series=%s-%s-%s", series, m_season, m_episode); + m_dupeKey[len-1] = '\0'; } - else if (iRageId != 0 && GetSeasonNum() != 0 && GetEpisodeNum() != 0) + else if (rageIdVal != 0 && GetSeasonNum() != 0 && GetEpisodeNum() != 0) { - m_szDupeKey = (char*)malloc(100); - snprintf(m_szDupeKey, 100, "rageid=%i-%s-%s", iRageId, m_szSeason, m_szEpisode); - m_szDupeKey[100-1] = '\0'; + m_dupeKey = (char*)malloc(100); + snprintf(m_dupeKey, 100, "rageid=%i-%s-%s", rageIdVal, m_season, m_episode); + m_dupeKey[100-1] = '\0'; } else { - m_szDupeKey = strdup(""); + m_dupeKey = strdup(""); } } int FeedItemInfo::GetSeasonNum() { - if (!m_szSeason && !m_bSeasonEpisodeParsed) + if (!m_season && !m_seasonEpisodeParsed) { ParseSeasonEpisode(); } - return m_iSeasonNum; + return m_seasonNum; } int FeedItemInfo::GetEpisodeNum() { - if (!m_szEpisode && !m_bSeasonEpisodeParsed) + if (!m_episode && !m_seasonEpisodeParsed) { ParseSeasonEpisode(); } - return m_iEpisodeNum; + return m_episodeNum; } void FeedItemInfo::ParseSeasonEpisode() { - m_bSeasonEpisodeParsed = true; + m_seasonEpisodeParsed = true; - RegEx** ppRegEx = m_pFeedFilterHelper->GetSeasonEpisodeRegEx(); + RegEx** ppRegEx = m_feedFilterHelper->GetSeasonEpisodeRegEx(); if (!*ppRegEx) { *ppRegEx = new RegEx("[^[:alnum:]]s?([0-9]+)[ex]([0-9]+(-?e[0-9]+)?)[^[:alnum:]]", 10); } - if ((*ppRegEx)->Match(m_szTitle)) + if ((*ppRegEx)->Match(m_title)) { - char szRegValue[100]; - char szValue[100]; + char regValue[100]; + char value[100]; - snprintf(szValue, 100, "S%02d", atoi(m_szTitle + (*ppRegEx)->GetMatchStart(1))); - szValue[100-1] = '\0'; - SetSeason(szValue); + snprintf(value, 100, "S%02d", atoi(m_title + (*ppRegEx)->GetMatchStart(1))); + value[100-1] = '\0'; + SetSeason(value); - int iLen = (*ppRegEx)->GetMatchLen(2); - iLen = iLen < 99 ? iLen : 99; - strncpy(szRegValue, m_szTitle + (*ppRegEx)->GetMatchStart(2), (*ppRegEx)->GetMatchLen(2)); - szRegValue[iLen] = '\0'; - snprintf(szValue, 100, "E%s", szRegValue); - szValue[100-1] = '\0'; - Util::ReduceStr(szValue, "-", ""); - for (char* p = szValue; *p; p++) *p = toupper(*p); // convert string to uppercase e02 -> E02 - SetEpisode(szValue); + int len = (*ppRegEx)->GetMatchLen(2); + len = len < 99 ? len : 99; + strncpy(regValue, m_title + (*ppRegEx)->GetMatchStart(2), (*ppRegEx)->GetMatchLen(2)); + regValue[len] = '\0'; + snprintf(value, 100, "E%s", regValue); + value[100-1] = '\0'; + Util::ReduceStr(value, "-", ""); + for (char* p = value; *p; p++) *p = toupper(*p); // convert string to uppercase e02 -> E02 + SetEpisode(value); } } const char* FeedItemInfo::GetDupeStatus() { - if (!m_szDupeStatus) + if (!m_dupeStatus) { - char szStatuses[200]; - szStatuses[0] = '\0'; - m_pFeedFilterHelper->CalcDupeStatus(m_szTitle, m_szDupeKey, szStatuses, sizeof(szStatuses)); - m_szDupeStatus = strdup(szStatuses); + char statuses[200]; + statuses[0] = '\0'; + m_feedFilterHelper->CalcDupeStatus(m_title, m_dupeKey, statuses, sizeof(statuses)); + m_dupeStatus = strdup(statuses); } - return m_szDupeStatus; + return m_dupeStatus; } -FeedHistoryInfo::FeedHistoryInfo(const char* szUrl, FeedHistoryInfo::EStatus eStatus, time_t tLastSeen) +FeedHistoryInfo::FeedHistoryInfo(const char* url, FeedHistoryInfo::EStatus status, time_t lastSeen) { - m_szUrl = szUrl ? strdup(szUrl) : NULL; - m_eStatus = eStatus; - m_tLastSeen = tLastSeen; + m_url = url ? strdup(url) : NULL; + m_status = status; + m_lastSeen = lastSeen; } FeedHistoryInfo::~FeedHistoryInfo() { - free(m_szUrl); + free(m_url); } @@ -368,33 +368,33 @@ void FeedHistory::Clear() clear(); } -void FeedHistory::Add(const char* szUrl, FeedHistoryInfo::EStatus eStatus, time_t tLastSeen) +void FeedHistory::Add(const char* url, FeedHistoryInfo::EStatus status, time_t lastSeen) { - push_back(new FeedHistoryInfo(szUrl, eStatus, tLastSeen)); + push_back(new FeedHistoryInfo(url, status, lastSeen)); } -void FeedHistory::Remove(const char* szUrl) +void FeedHistory::Remove(const char* url) { for (iterator it = begin(); it != end(); it++) { - FeedHistoryInfo* pFeedHistoryInfo = *it; - if (!strcmp(pFeedHistoryInfo->GetUrl(), szUrl)) + FeedHistoryInfo* feedHistoryInfo = *it; + if (!strcmp(feedHistoryInfo->GetUrl(), url)) { - delete pFeedHistoryInfo; + delete feedHistoryInfo; erase(it); break; } } } -FeedHistoryInfo* FeedHistory::Find(const char* szUrl) +FeedHistoryInfo* FeedHistory::Find(const char* url) { for (iterator it = begin(); it != end(); it++) { - FeedHistoryInfo* pFeedHistoryInfo = *it; - if (!strcmp(pFeedHistoryInfo->GetUrl(), szUrl)) + FeedHistoryInfo* feedHistoryInfo = *it; + if (!strcmp(feedHistoryInfo->GetUrl(), url)) { - return pFeedHistoryInfo; + return feedHistoryInfo; } } @@ -406,7 +406,7 @@ FeedItemInfos::FeedItemInfos() { debug("Creating FeedItemInfos"); - m_iRefCount = 0; + m_refCount = 0; } FeedItemInfos::~FeedItemInfos() @@ -421,19 +421,19 @@ FeedItemInfos::~FeedItemInfos() void FeedItemInfos::Retain() { - m_iRefCount++; + m_refCount++; } void FeedItemInfos::Release() { - m_iRefCount--; - if (m_iRefCount <= 0) + m_refCount--; + if (m_refCount <= 0) { delete this; } } -void FeedItemInfos::Add(FeedItemInfo* pFeedItemInfo) +void FeedItemInfos::Add(FeedItemInfo* feedItemInfo) { - push_back(pFeedItemInfo); + push_back(feedItemInfo); } diff --git a/daemon/feed/FeedInfo.h b/daemon/feed/FeedInfo.h index e98dd324..d2a967e1 100644 --- a/daemon/feed/FeedInfo.h +++ b/daemon/feed/FeedInfo.h @@ -45,53 +45,53 @@ public: }; private: - int m_iID; - char* m_szName; - char* m_szUrl; - int m_iInterval; - char* m_szFilter; - unsigned int m_iFilterHash; - bool m_bPauseNzb; - char* m_szCategory; - char* m_szFeedScript; - int m_iPriority; - time_t m_tLastUpdate; - bool m_bPreview; - EStatus m_eStatus; - char* m_szOutputFilename; - bool m_bFetch; - bool m_bForce; - bool m_bBacklog; + int m_id; + char* m_name; + char* m_url; + int m_interval; + char* m_filter; + unsigned int m_filterHash; + bool m_pauseNzb; + char* m_category; + char* m_feedScript; + int m_priority; + time_t m_lastUpdate; + bool m_preview; + EStatus m_status; + char* m_outputFilename; + bool m_fetch; + bool m_force; + bool m_backlog; public: - FeedInfo(int iID, const char* szName, const char* szUrl, bool bBacklog, int iInterval, - const char* szFilter, bool bPauseNzb, const char* szCategory, int iPriority, - const char* szFeedScript); + FeedInfo(int id, const char* name, const char* url, bool backlog, int interval, + const char* filter, bool pauseNzb, const char* category, int priority, + const char* feedScript); ~FeedInfo(); - int GetID() { return m_iID; } - const char* GetName() { return m_szName; } - const char* GetUrl() { return m_szUrl; } - int GetInterval() { return m_iInterval; } - const char* GetFilter() { return m_szFilter; } - unsigned int GetFilterHash() { return m_iFilterHash; } - bool GetPauseNzb() { return m_bPauseNzb; } - const char* GetCategory() { return m_szCategory; } - int GetPriority() { return m_iPriority; } - const char* GetFeedScript() { return m_szFeedScript; } - time_t GetLastUpdate() { return m_tLastUpdate; } - void SetLastUpdate(time_t tLastUpdate) { m_tLastUpdate = tLastUpdate; } - bool GetPreview() { return m_bPreview; } - void SetPreview(bool bPreview) { m_bPreview = bPreview; } - EStatus GetStatus() { return m_eStatus; } - void SetStatus(EStatus Status) { m_eStatus = Status; } - const char* GetOutputFilename() { return m_szOutputFilename; } - void SetOutputFilename(const char* szOutputFilename); - bool GetFetch() { return m_bFetch; } - void SetFetch(bool bFetch) { m_bFetch = bFetch; } - bool GetForce() { return m_bForce; } - void SetForce(bool bForce) { m_bForce = bForce; } - bool GetBacklog() { return m_bBacklog; } - void SetBacklog(bool bBacklog) { m_bBacklog = bBacklog; } + int GetID() { return m_id; } + const char* GetName() { return m_name; } + const char* GetUrl() { return m_url; } + int GetInterval() { return m_interval; } + const char* GetFilter() { return m_filter; } + unsigned int GetFilterHash() { return m_filterHash; } + bool GetPauseNzb() { return m_pauseNzb; } + const char* GetCategory() { return m_category; } + int GetPriority() { return m_priority; } + const char* GetFeedScript() { return m_feedScript; } + time_t GetLastUpdate() { return m_lastUpdate; } + void SetLastUpdate(time_t lastUpdate) { m_lastUpdate = lastUpdate; } + bool GetPreview() { return m_preview; } + void SetPreview(bool preview) { m_preview = preview; } + EStatus GetStatus() { return m_status; } + void SetStatus(EStatus Status) { m_status = Status; } + const char* GetOutputFilename() { return m_outputFilename; } + void SetOutputFilename(const char* outputFilename); + bool GetFetch() { return m_fetch; } + void SetFetch(bool fetch) { m_fetch = fetch; } + bool GetForce() { return m_force; } + void SetForce(bool force) { m_force = force; } + bool GetBacklog() { return m_backlog; } + void SetBacklog(bool backlog) { m_backlog = backlog; } }; typedef std::deque Feeds; @@ -100,7 +100,7 @@ class FeedFilterHelper { public: virtual RegEx** GetSeasonEpisodeRegEx() = 0; - virtual void CalcDupeStatus(const char* szTitle, const char* szDupeKey, char* szStatusBuf, int iBufLen) = 0; + virtual void CalcDupeStatus(const char* title, const char* dupeKey, char* statusBuf, int bufLen) = 0; }; class FeedItemInfo @@ -124,13 +124,13 @@ public: class Attr { private: - char* m_szName; - char* m_szValue; + char* m_name; + char* m_value; public: - Attr(const char* szName, const char* szValue); + Attr(const char* name, const char* value); ~Attr(); - const char* GetName() { return m_szName; } - const char* GetValue() { return m_szValue; } + const char* GetName() { return m_name; } + const char* GetValue() { return m_value; } }; typedef std::deque AttributesBase; @@ -139,91 +139,91 @@ public: { public: ~Attributes(); - void Add(const char* szName, const char* szValue); - Attr* Find(const char* szName); + void Add(const char* name, const char* value); + Attr* Find(const char* name); }; private: - char* m_szTitle; - char* m_szFilename; - char* m_szUrl; - time_t m_tTime; - long long m_lSize; - char* m_szCategory; - int m_iImdbId; - int m_iRageId; - char* m_szDescription; - char* m_szSeason; - char* m_szEpisode; - int m_iSeasonNum; - int m_iEpisodeNum; - bool m_bSeasonEpisodeParsed; - char* m_szAddCategory; - bool m_bPauseNzb; - int m_iPriority; - EStatus m_eStatus; - EMatchStatus m_eMatchStatus; - int m_iMatchRule; - char* m_szDupeKey; - int m_iDupeScore; - EDupeMode m_eDupeMode; - char* m_szDupeStatus; - FeedFilterHelper* m_pFeedFilterHelper; - Attributes m_Attributes; + char* m_title; + char* m_filename; + char* m_url; + time_t m_time; + long long m_size; + char* m_category; + int m_imdbId; + int m_rageId; + char* m_description; + char* m_season; + char* m_episode; + int m_seasonNum; + int m_episodeNum; + bool m_seasonEpisodeParsed; + char* m_addCategory; + bool m_pauseNzb; + int m_priority; + EStatus m_status; + EMatchStatus m_matchStatus; + int m_matchRule; + char* m_dupeKey; + int m_dupeScore; + EDupeMode m_dupeMode; + char* m_dupeStatus; + FeedFilterHelper* m_feedFilterHelper; + Attributes m_attributes; - int ParsePrefixedInt(const char *szValue); + int ParsePrefixedInt(const char *value); void ParseSeasonEpisode(); public: FeedItemInfo(); ~FeedItemInfo(); - void SetFeedFilterHelper(FeedFilterHelper* pFeedFilterHelper) { m_pFeedFilterHelper = pFeedFilterHelper; } - const char* GetTitle() { return m_szTitle; } - void SetTitle(const char* szTitle); - const char* GetFilename() { return m_szFilename; } - void SetFilename(const char* szFilename); - const char* GetUrl() { return m_szUrl; } - void SetUrl(const char* szUrl); - long long GetSize() { return m_lSize; } - void SetSize(long long lSize) { m_lSize = lSize; } - const char* GetCategory() { return m_szCategory; } - void SetCategory(const char* szCategory); - int GetImdbId() { return m_iImdbId; } - void SetImdbId(int iImdbId) { m_iImdbId = iImdbId; } - int GetRageId() { return m_iRageId; } - void SetRageId(int iRageId) { m_iRageId = iRageId; } - const char* GetDescription() { return m_szDescription; } - void SetDescription(const char* szDescription); - const char* GetSeason() { return m_szSeason; } - void SetSeason(const char* szSeason); - const char* GetEpisode() { return m_szEpisode; } - void SetEpisode(const char* szEpisode); + void SetFeedFilterHelper(FeedFilterHelper* feedFilterHelper) { m_feedFilterHelper = feedFilterHelper; } + const char* GetTitle() { return m_title; } + void SetTitle(const char* title); + const char* GetFilename() { return m_filename; } + void SetFilename(const char* filename); + const char* GetUrl() { return m_url; } + void SetUrl(const char* url); + long long GetSize() { return m_size; } + void SetSize(long long size) { m_size = size; } + const char* GetCategory() { return m_category; } + void SetCategory(const char* category); + int GetImdbId() { return m_imdbId; } + void SetImdbId(int imdbId) { m_imdbId = imdbId; } + int GetRageId() { return m_rageId; } + void SetRageId(int rageId) { m_rageId = rageId; } + const char* GetDescription() { return m_description; } + void SetDescription(const char* description); + const char* GetSeason() { return m_season; } + void SetSeason(const char* season); + const char* GetEpisode() { return m_episode; } + void SetEpisode(const char* episode); int GetSeasonNum(); int GetEpisodeNum(); - const char* GetAddCategory() { return m_szAddCategory; } - void SetAddCategory(const char* szAddCategory); - bool GetPauseNzb() { return m_bPauseNzb; } - void SetPauseNzb(bool bPauseNzb) { m_bPauseNzb = bPauseNzb; } - int GetPriority() { return m_iPriority; } - void SetPriority(int iPriority) { m_iPriority = iPriority; } - time_t GetTime() { return m_tTime; } - void SetTime(time_t tTime) { m_tTime = tTime; } - EStatus GetStatus() { return m_eStatus; } - void SetStatus(EStatus eStatus) { m_eStatus = eStatus; } - EMatchStatus GetMatchStatus() { return m_eMatchStatus; } - void SetMatchStatus(EMatchStatus eMatchStatus) { m_eMatchStatus = eMatchStatus; } - int GetMatchRule() { return m_iMatchRule; } - void SetMatchRule(int iMatchRule) { m_iMatchRule = iMatchRule; } - const char* GetDupeKey() { return m_szDupeKey; } - void SetDupeKey(const char* szDupeKey); - void AppendDupeKey(const char* szExtraDupeKey); - void BuildDupeKey(const char* szRageId, const char* szSeries); - int GetDupeScore() { return m_iDupeScore; } - void SetDupeScore(int iDupeScore) { m_iDupeScore = iDupeScore; } - EDupeMode GetDupeMode() { return m_eDupeMode; } - void SetDupeMode(EDupeMode eDupeMode) { m_eDupeMode = eDupeMode; } + const char* GetAddCategory() { return m_addCategory; } + void SetAddCategory(const char* addCategory); + bool GetPauseNzb() { return m_pauseNzb; } + void SetPauseNzb(bool pauseNzb) { m_pauseNzb = pauseNzb; } + int GetPriority() { return m_priority; } + void SetPriority(int priority) { m_priority = priority; } + time_t GetTime() { return m_time; } + void SetTime(time_t time) { m_time = time; } + EStatus GetStatus() { return m_status; } + void SetStatus(EStatus status) { m_status = status; } + EMatchStatus GetMatchStatus() { return m_matchStatus; } + void SetMatchStatus(EMatchStatus matchStatus) { m_matchStatus = matchStatus; } + int GetMatchRule() { return m_matchRule; } + void SetMatchRule(int matchRule) { m_matchRule = matchRule; } + const char* GetDupeKey() { return m_dupeKey; } + void SetDupeKey(const char* dupeKey); + void AppendDupeKey(const char* extraDupeKey); + void BuildDupeKey(const char* rageId, const char* series); + int GetDupeScore() { return m_dupeScore; } + void SetDupeScore(int dupeScore) { m_dupeScore = dupeScore; } + EDupeMode GetDupeMode() { return m_dupeMode; } + void SetDupeMode(EDupeMode dupeMode) { m_dupeMode = dupeMode; } const char* GetDupeStatus(); - Attributes* GetAttributes() { return &m_Attributes; } + Attributes* GetAttributes() { return &m_attributes; } }; typedef std::deque FeedItemInfosBase; @@ -231,14 +231,14 @@ typedef std::deque FeedItemInfosBase; class FeedItemInfos : public FeedItemInfosBase { private: - int m_iRefCount; + int m_refCount; public: FeedItemInfos(); ~FeedItemInfos(); void Retain(); void Release(); - void Add(FeedItemInfo* pFeedItemInfo); + void Add(FeedItemInfo* feedItemInfo); }; class FeedHistoryInfo @@ -252,18 +252,18 @@ public: }; private: - char* m_szUrl; - EStatus m_eStatus; - time_t m_tLastSeen; + char* m_url; + EStatus m_status; + time_t m_lastSeen; public: - FeedHistoryInfo(const char* szUrl, EStatus eStatus, time_t tLastSeen); + FeedHistoryInfo(const char* url, EStatus status, time_t lastSeen); ~FeedHistoryInfo(); - const char* GetUrl() { return m_szUrl; } - EStatus GetStatus() { return m_eStatus; } - void SetStatus(EStatus Status) { m_eStatus = Status; } - time_t GetLastSeen() { return m_tLastSeen; } - void SetLastSeen(time_t tLastSeen) { m_tLastSeen = tLastSeen; } + const char* GetUrl() { return m_url; } + EStatus GetStatus() { return m_status; } + void SetStatus(EStatus Status) { m_status = Status; } + time_t GetLastSeen() { return m_lastSeen; } + void SetLastSeen(time_t lastSeen) { m_lastSeen = lastSeen; } }; typedef std::deque FeedHistoryBase; @@ -273,9 +273,9 @@ class FeedHistory : public FeedHistoryBase public: ~FeedHistory(); void Clear(); - void Add(const char* szUrl, FeedHistoryInfo::EStatus eStatus, time_t tLastSeen); - void Remove(const char* szUrl); - FeedHistoryInfo* Find(const char* szUrl); + void Add(const char* url, FeedHistoryInfo::EStatus status, time_t lastSeen); + void Remove(const char* url); + FeedHistoryInfo* Find(const char* url); }; #endif diff --git a/daemon/frontend/ColoredFrontend.cpp b/daemon/frontend/ColoredFrontend.cpp index d22f0943..7b1a7e3d 100644 --- a/daemon/frontend/ColoredFrontend.cpp +++ b/daemon/frontend/ColoredFrontend.cpp @@ -45,8 +45,8 @@ ColoredFrontend::ColoredFrontend() { - m_bSummary = true; - m_bNeedGoBack = false; + m_summary = true; + m_needGoBack = false; #ifdef WIN32 m_hConsole = GetStdHandle(STD_OUTPUT_HANDLE); #endif @@ -54,7 +54,7 @@ ColoredFrontend::ColoredFrontend() void ColoredFrontend::BeforePrint() { - if (m_bNeedGoBack) + if (m_needGoBack) { // go back one line #ifdef WIN32 @@ -65,7 +65,7 @@ void ColoredFrontend::BeforePrint() #else printf("\r\033[1A"); #endif - m_bNeedGoBack = false; + m_needGoBack = false; } } @@ -74,60 +74,60 @@ void ColoredFrontend::PrintStatus() char tmp[1024]; char timeString[100]; timeString[0] = '\0'; - int iCurrentDownloadSpeed = m_bStandBy ? 0 : m_iCurrentDownloadSpeed; + int currentDownloadSpeed = m_standBy ? 0 : m_currentDownloadSpeed; - if (iCurrentDownloadSpeed > 0 && !m_bPauseDownload) + if (currentDownloadSpeed > 0 && !m_pauseDownload) { - long long remain_sec = (long long)(m_lRemainingSize / iCurrentDownloadSpeed); + long long remain_sec = (long long)(m_remainingSize / currentDownloadSpeed); int h = (int)(remain_sec / 3600); int m = (int)((remain_sec % 3600) / 60); int s = (int)(remain_sec % 60); sprintf(timeString, " (~ %.2d:%.2d:%.2d)", h, m, s); } - char szDownloadLimit[128]; - if (m_iDownloadLimit > 0) + char downloadLimit[128]; + if (m_downloadLimit > 0) { - sprintf(szDownloadLimit, ", Limit %i KB/s", m_iDownloadLimit / 1024); + sprintf(downloadLimit, ", Limit %i KB/s", m_downloadLimit / 1024); } else { - szDownloadLimit[0] = 0; + downloadLimit[0] = 0; } - char szPostStatus[128]; - if (m_iPostJobCount > 0) + char postStatus[128]; + if (m_postJobCount > 0) { - sprintf(szPostStatus, ", %i post-job%s", m_iPostJobCount, m_iPostJobCount > 1 ? "s" : ""); + sprintf(postStatus, ", %i post-job%s", m_postJobCount, m_postJobCount > 1 ? "s" : ""); } else { - szPostStatus[0] = 0; + postStatus[0] = 0; } #ifdef WIN32 - char* szControlSeq = ""; + char* controlSeq = ""; #else printf("\033[s"); - const char* szControlSeq = "\033[K"; + const char* controlSeq = "\033[K"; #endif - char szFileSize[20]; - char szCurrendSpeed[20]; + char fileSize[20]; + char currendSpeed[20]; snprintf(tmp, 1024, " %d threads, %s, %s remaining%s%s%s%s%s\n", - m_iThreadCount, Util::FormatSpeed(szCurrendSpeed, sizeof(szCurrendSpeed), iCurrentDownloadSpeed), - Util::FormatSize(szFileSize, sizeof(szFileSize), m_lRemainingSize), - timeString, szPostStatus, m_bPauseDownload ? (m_bStandBy ? ", Paused" : ", Pausing") : "", - szDownloadLimit, szControlSeq); + m_threadCount, Util::FormatSpeed(currendSpeed, sizeof(currendSpeed), currentDownloadSpeed), + Util::FormatSize(fileSize, sizeof(fileSize), m_remainingSize), + timeString, postStatus, m_pauseDownload ? (m_standBy ? ", Paused" : ", Pausing") : "", + downloadLimit, controlSeq); tmp[1024-1] = '\0'; printf("%s", tmp); - m_bNeedGoBack = true; + m_needGoBack = true; } -void ColoredFrontend::PrintMessage(Message * pMessage) +void ColoredFrontend::PrintMessage(Message * message) { #ifdef WIN32 - switch (pMessage->GetKind()) + switch (message->GetKind()) { case Message::mkDebug: SetConsoleTextAttribute(m_hConsole, 8); @@ -151,13 +151,13 @@ void ColoredFrontend::PrintMessage(Message * pMessage) break; } SetConsoleTextAttribute(m_hConsole, 7); - char* msg = strdup(pMessage->GetText()); + char* msg = strdup(message->GetText()); CharToOem(msg, msg); printf(" %s\n", msg); free(msg); #else - const char* msg = pMessage->GetText(); - switch (pMessage->GetKind()) + const char* msg = message->GetText(); + switch (message->GetKind()) { case Message::mkDebug: printf("[DEBUG] %s\033[K\n", msg); diff --git a/daemon/frontend/ColoredFrontend.h b/daemon/frontend/ColoredFrontend.h index 0dbcfdb8..247a7525 100644 --- a/daemon/frontend/ColoredFrontend.h +++ b/daemon/frontend/ColoredFrontend.h @@ -33,7 +33,7 @@ class ColoredFrontend : public LoggableFrontend { private: - bool m_bNeedGoBack; + bool m_needGoBack; #ifdef WIN32 HANDLE m_hConsole; @@ -41,7 +41,7 @@ private: protected: virtual void BeforePrint(); - virtual void PrintMessage(Message* pMessage); + virtual void PrintMessage(Message* message); virtual void PrintStatus(); virtual void PrintSkip(); virtual void BeforeExit(); diff --git a/daemon/frontend/Frontend.cpp b/daemon/frontend/Frontend.cpp index 91e8a5ff..a59a78ed 100644 --- a/daemon/frontend/Frontend.cpp +++ b/daemon/frontend/Frontend.cpp @@ -55,21 +55,21 @@ Frontend::Frontend() { debug("Creating Frontend"); - m_iNeededLogFirstID = 0; - m_iNeededLogEntries = 0; - m_bSummary = false; - m_bFileList = false; - m_iCurrentDownloadSpeed = 0; - m_lRemainingSize = 0; - m_bPauseDownload = false; - m_iDownloadLimit = 0; - m_iThreadCount = 0; - m_iPostJobCount = 0; - m_iUpTimeSec = 0; - m_iDnTimeSec = 0; - m_iAllBytes = 0; - m_bStandBy = 0; - m_iUpdateInterval = g_pOptions->GetUpdateInterval(); + m_neededLogFirstId = 0; + m_neededLogEntries = 0; + m_summary = false; + m_fileList = false; + m_currentDownloadSpeed = 0; + m_remainingSize = 0; + m_pauseDownload = false; + m_downloadLimit = 0; + m_threadCount = 0; + m_postJobCount = 0; + m_upTimeSec = 0; + m_dnTimeSec = 0; + m_allBytes = 0; + m_standBy = 0; + m_updateInterval = g_pOptions->GetUpdateInterval(); } bool Frontend::PrepareData() @@ -80,32 +80,32 @@ bool Frontend::PrepareData() { return false; } - if (!RequestMessages() || ((m_bSummary || m_bFileList) && !RequestFileList())) + if (!RequestMessages() || ((m_summary || m_fileList) && !RequestFileList())) { - const char* szControlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); - printf("\nUnable to send request to nzbget-server at %s (port %i) \n", szControlIP, g_pOptions->GetControlPort()); + const char* controlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); + printf("\nUnable to send request to nzbget-server at %s (port %i) \n", controlIP, g_pOptions->GetControlPort()); Stop(); return false; } } else { - if (m_bSummary) + if (m_summary) { - m_iCurrentDownloadSpeed = g_pStatMeter->CalcCurrentDownloadSpeed(); - m_bPauseDownload = g_pOptions->GetPauseDownload(); - m_iDownloadLimit = g_pOptions->GetDownloadRate(); - m_iThreadCount = Thread::GetThreadCount(); - g_pStatMeter->CalcTotalStat(&m_iUpTimeSec, &m_iDnTimeSec, &m_iAllBytes, &m_bStandBy); + m_currentDownloadSpeed = g_pStatMeter->CalcCurrentDownloadSpeed(); + m_pauseDownload = g_pOptions->GetPauseDownload(); + m_downloadLimit = g_pOptions->GetDownloadRate(); + m_threadCount = Thread::GetThreadCount(); + g_pStatMeter->CalcTotalStat(&m_upTimeSec, &m_dnTimeSec, &m_allBytes, &m_standBy); - DownloadQueue *pDownloadQueue = DownloadQueue::Lock(); - m_iPostJobCount = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + DownloadQueue *downloadQueue = DownloadQueue::Lock(); + m_postJobCount = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - m_iPostJobCount += pNZBInfo->GetPostInfo() ? 1 : 0; + NZBInfo* nzbInfo = *it; + m_postJobCount += nzbInfo->GetPostInfo() ? 1 : 0; } - pDownloadQueue->CalcRemainingSize(&m_lRemainingSize, NULL); + downloadQueue->CalcRemainingSize(&m_remainingSize, NULL); DownloadQueue::Unlock(); } @@ -117,10 +117,10 @@ void Frontend::FreeData() { if (IsRemoteMode()) { - m_RemoteMessages.Clear(); + m_remoteMessages.Clear(); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - pDownloadQueue->GetQueue()->Clear(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + downloadQueue->GetQueue()->Clear(); DownloadQueue::Unlock(); } } @@ -129,7 +129,7 @@ MessageList* Frontend::LockMessages() { if (IsRemoteMode()) { - return &m_RemoteMessages; + return &m_remoteMessages; } else { @@ -160,64 +160,64 @@ bool Frontend::IsRemoteMode() return g_pOptions->GetRemoteClientMode(); } -void Frontend::ServerPauseUnpause(bool bPause) +void Frontend::ServerPauseUnpause(bool pause) { if (IsRemoteMode()) { - RequestPauseUnpause(bPause); + RequestPauseUnpause(pause); } else { g_pOptions->SetResumeTime(0); - g_pOptions->SetPauseDownload(bPause); + g_pOptions->SetPauseDownload(pause); } } -void Frontend::ServerSetDownloadRate(int iRate) +void Frontend::ServerSetDownloadRate(int rate) { if (IsRemoteMode()) { - RequestSetDownloadRate(iRate); + RequestSetDownloadRate(rate); } else { - g_pOptions->SetDownloadRate(iRate); + g_pOptions->SetDownloadRate(rate); } } -bool Frontend::ServerEditQueue(DownloadQueue::EEditAction eAction, int iOffset, int iID) +bool Frontend::ServerEditQueue(DownloadQueue::EEditAction action, int offset, int id) { if (IsRemoteMode()) { - return RequestEditQueue(eAction, iOffset, iID); + return RequestEditQueue(action, offset, id); } else { - DownloadQueue* pDownloadQueue = LockQueue(); - bool bOK = pDownloadQueue->EditEntry(iID, eAction, iOffset, NULL); + DownloadQueue* downloadQueue = LockQueue(); + bool ok = downloadQueue->EditEntry(id, action, offset, NULL); UnlockQueue(); - return bOK; + return ok; } return false; } -void Frontend::InitMessageBase(SNZBRequestBase* pMessageBase, int iRequest, int iSize) +void Frontend::InitMessageBase(SNZBRequestBase* messageBase, int request, int size) { - pMessageBase->m_iSignature = htonl(NZBMESSAGE_SIGNATURE); - pMessageBase->m_iType = htonl(iRequest); - pMessageBase->m_iStructSize = htonl(iSize); + messageBase->m_signature = htonl(NZBMESSAGE_SIGNATURE); + messageBase->m_type = htonl(request); + messageBase->m_structSize = htonl(size); - strncpy(pMessageBase->m_szUsername, g_pOptions->GetControlUsername(), NZBREQUESTPASSWORDSIZE - 1); - pMessageBase->m_szUsername[NZBREQUESTPASSWORDSIZE - 1] = '\0'; + strncpy(messageBase->m_username, g_pOptions->GetControlUsername(), NZBREQUESTPASSWORDSIZE - 1); + messageBase->m_username[NZBREQUESTPASSWORDSIZE - 1] = '\0'; - strncpy(pMessageBase->m_szPassword, g_pOptions->GetControlPassword(), NZBREQUESTPASSWORDSIZE); - pMessageBase->m_szPassword[NZBREQUESTPASSWORDSIZE - 1] = '\0'; + strncpy(messageBase->m_password, g_pOptions->GetControlPassword(), NZBREQUESTPASSWORDSIZE); + messageBase->m_password[NZBREQUESTPASSWORDSIZE - 1] = '\0'; } bool Frontend::RequestMessages() { - const char* szControlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); - Connection connection(szControlIP, g_pOptions->GetControlPort(), false); + const char* controlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); + Connection connection(controlIP, g_pOptions->GetControlPort(), false); bool OK = connection.Connect(); if (!OK) @@ -226,15 +226,15 @@ bool Frontend::RequestMessages() } SNZBLogRequest LogRequest; - InitMessageBase(&LogRequest.m_MessageBase, eRemoteRequestLog, sizeof(LogRequest)); - LogRequest.m_iLines = htonl(m_iNeededLogEntries); - if (m_iNeededLogEntries == 0) + InitMessageBase(&LogRequest.m_messageBase, remoteRequestLog, sizeof(LogRequest)); + LogRequest.m_lines = htonl(m_neededLogEntries); + if (m_neededLogEntries == 0) { - LogRequest.m_iIDFrom = htonl(m_iNeededLogFirstID > 0 ? m_iNeededLogFirstID : 1); + LogRequest.m_idFrom = htonl(m_neededLogFirstId > 0 ? m_neededLogFirstId : 1); } else { - LogRequest.m_iIDFrom = 0; + LogRequest.m_idFrom = 0; } if (!connection.Send((char*)(&LogRequest), sizeof(LogRequest))) @@ -244,43 +244,43 @@ bool Frontend::RequestMessages() // Now listen for the returned log SNZBLogResponse LogResponse; - bool bRead = connection.Recv((char*) &LogResponse, sizeof(LogResponse)); - if (!bRead || - (int)ntohl(LogResponse.m_MessageBase.m_iSignature) != (int)NZBMESSAGE_SIGNATURE || - ntohl(LogResponse.m_MessageBase.m_iStructSize) != sizeof(LogResponse)) + bool read = connection.Recv((char*) &LogResponse, sizeof(LogResponse)); + if (!read || + (int)ntohl(LogResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || + ntohl(LogResponse.m_messageBase.m_structSize) != sizeof(LogResponse)) { return false; } - char* pBuf = NULL; - if (ntohl(LogResponse.m_iTrailingDataLength) > 0) + char* buf = NULL; + if (ntohl(LogResponse.m_trailingDataLength) > 0) { - pBuf = (char*)malloc(ntohl(LogResponse.m_iTrailingDataLength)); - if (!connection.Recv(pBuf, ntohl(LogResponse.m_iTrailingDataLength))) + buf = (char*)malloc(ntohl(LogResponse.m_trailingDataLength)); + if (!connection.Recv(buf, ntohl(LogResponse.m_trailingDataLength))) { - free(pBuf); + free(buf); return false; } } connection.Disconnect(); - if (ntohl(LogResponse.m_iTrailingDataLength) > 0) + if (ntohl(LogResponse.m_trailingDataLength) > 0) { - char* pBufPtr = (char*)pBuf; - for (unsigned int i = 0; i < ntohl(LogResponse.m_iNrTrailingEntries); i++) + char* bufPtr = (char*)buf; + for (unsigned int i = 0; i < ntohl(LogResponse.m_nrTrailingEntries); i++) { - SNZBLogResponseEntry* pLogAnswer = (SNZBLogResponseEntry*) pBufPtr; + SNZBLogResponseEntry* logAnswer = (SNZBLogResponseEntry*) bufPtr; - char* szText = pBufPtr + sizeof(SNZBLogResponseEntry); + char* text = bufPtr + sizeof(SNZBLogResponseEntry); - Message* pMessage = new Message(ntohl(pLogAnswer->m_iID), (Message::EKind)ntohl(pLogAnswer->m_iKind), ntohl(pLogAnswer->m_tTime), szText); - m_RemoteMessages.push_back(pMessage); + Message* message = new Message(ntohl(logAnswer->m_id), (Message::EKind)ntohl(logAnswer->m_kind), ntohl(logAnswer->m_time), text); + m_remoteMessages.push_back(message); - pBufPtr += sizeof(SNZBLogResponseEntry) + ntohl(pLogAnswer->m_iTextLen); + bufPtr += sizeof(SNZBLogResponseEntry) + ntohl(logAnswer->m_textLen); } - free(pBuf); + free(buf); } return true; @@ -288,8 +288,8 @@ bool Frontend::RequestMessages() bool Frontend::RequestFileList() { - const char* szControlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); - Connection connection(szControlIP, g_pOptions->GetControlPort(), false); + const char* controlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); + Connection connection(controlIP, g_pOptions->GetControlPort(), false); bool OK = connection.Connect(); if (!OK) @@ -298,9 +298,9 @@ bool Frontend::RequestFileList() } SNZBListRequest ListRequest; - InitMessageBase(&ListRequest.m_MessageBase, eRemoteRequestList, sizeof(ListRequest)); - ListRequest.m_bFileList = htonl(m_bFileList); - ListRequest.m_bServerState = htonl(m_bSummary); + InitMessageBase(&ListRequest.m_messageBase, remoteRequestList, sizeof(ListRequest)); + ListRequest.m_fileList = htonl(m_fileList); + ListRequest.m_serverState = htonl(m_summary); if (!connection.Send((char*)(&ListRequest), sizeof(ListRequest))) { @@ -309,76 +309,76 @@ bool Frontend::RequestFileList() // Now listen for the returned list SNZBListResponse ListResponse; - bool bRead = connection.Recv((char*) &ListResponse, sizeof(ListResponse)); - if (!bRead || - (int)ntohl(ListResponse.m_MessageBase.m_iSignature) != (int)NZBMESSAGE_SIGNATURE || - ntohl(ListResponse.m_MessageBase.m_iStructSize) != sizeof(ListResponse)) + bool read = connection.Recv((char*) &ListResponse, sizeof(ListResponse)); + if (!read || + (int)ntohl(ListResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || + ntohl(ListResponse.m_messageBase.m_structSize) != sizeof(ListResponse)) { return false; } - char* pBuf = NULL; - if (ntohl(ListResponse.m_iTrailingDataLength) > 0) + char* buf = NULL; + if (ntohl(ListResponse.m_trailingDataLength) > 0) { - pBuf = (char*)malloc(ntohl(ListResponse.m_iTrailingDataLength)); - if (!connection.Recv(pBuf, ntohl(ListResponse.m_iTrailingDataLength))) + buf = (char*)malloc(ntohl(ListResponse.m_trailingDataLength)); + if (!connection.Recv(buf, ntohl(ListResponse.m_trailingDataLength))) { - free(pBuf); + free(buf); return false; } } connection.Disconnect(); - if (m_bSummary) + if (m_summary) { - m_bPauseDownload = ntohl(ListResponse.m_bDownloadPaused); - m_lRemainingSize = Util::JoinInt64(ntohl(ListResponse.m_iRemainingSizeHi), ntohl(ListResponse.m_iRemainingSizeLo)); - m_iCurrentDownloadSpeed = ntohl(ListResponse.m_iDownloadRate); - m_iDownloadLimit = ntohl(ListResponse.m_iDownloadLimit); - m_iThreadCount = ntohl(ListResponse.m_iThreadCount); - m_iPostJobCount = ntohl(ListResponse.m_iPostJobCount); - m_iUpTimeSec = ntohl(ListResponse.m_iUpTimeSec); - m_iDnTimeSec = ntohl(ListResponse.m_iDownloadTimeSec); - m_bStandBy = ntohl(ListResponse.m_bDownloadStandBy); - m_iAllBytes = Util::JoinInt64(ntohl(ListResponse.m_iDownloadedBytesHi), ntohl(ListResponse.m_iDownloadedBytesLo)); + m_pauseDownload = ntohl(ListResponse.m_downloadPaused); + m_remainingSize = Util::JoinInt64(ntohl(ListResponse.m_remainingSizeHi), ntohl(ListResponse.m_remainingSizeLo)); + m_currentDownloadSpeed = ntohl(ListResponse.m_downloadRate); + m_downloadLimit = ntohl(ListResponse.m_downloadLimit); + m_threadCount = ntohl(ListResponse.m_threadCount); + m_postJobCount = ntohl(ListResponse.m_postJobCount); + m_upTimeSec = ntohl(ListResponse.m_upTimeSec); + m_dnTimeSec = ntohl(ListResponse.m_downloadTimeSec); + m_standBy = ntohl(ListResponse.m_downloadStandBy); + m_allBytes = Util::JoinInt64(ntohl(ListResponse.m_downloadedBytesHi), ntohl(ListResponse.m_downloadedBytesLo)); } - if (m_bFileList && ntohl(ListResponse.m_iTrailingDataLength) > 0) + if (m_fileList && ntohl(ListResponse.m_trailingDataLength) > 0) { RemoteClient client; client.SetVerbose(false); - DownloadQueue* pDownloadQueue = LockQueue(); - client.BuildFileList(&ListResponse, pBuf, pDownloadQueue); + DownloadQueue* downloadQueue = LockQueue(); + client.BuildFileList(&ListResponse, buf, downloadQueue); UnlockQueue(); } - if (pBuf) + if (buf) { - free(pBuf); + free(buf); } return true; } -bool Frontend::RequestPauseUnpause(bool bPause) +bool Frontend::RequestPauseUnpause(bool pause) { RemoteClient client; client.SetVerbose(false); - return client.RequestServerPauseUnpause(bPause, eRemotePauseUnpauseActionDownload); + return client.RequestServerPauseUnpause(pause, remotePauseUnpauseActionDownload); } -bool Frontend::RequestSetDownloadRate(int iRate) +bool Frontend::RequestSetDownloadRate(int rate) { RemoteClient client; client.SetVerbose(false); - return client.RequestServerSetDownloadRate(iRate); + return client.RequestServerSetDownloadRate(rate); } -bool Frontend::RequestEditQueue(DownloadQueue::EEditAction eAction, int iOffset, int iID) +bool Frontend::RequestEditQueue(DownloadQueue::EEditAction action, int offset, int id) { RemoteClient client; client.SetVerbose(false); - return client.RequestServerEditQueue(eAction, iOffset, NULL, &iID, 1, NULL, eRemoteMatchModeID); + return client.RequestServerEditQueue(action, offset, NULL, &id, 1, NULL, remoteMatchModeId); } diff --git a/daemon/frontend/Frontend.h b/daemon/frontend/Frontend.h index 85d5e3bf..e950ea8a 100644 --- a/daemon/frontend/Frontend.h +++ b/daemon/frontend/Frontend.h @@ -36,29 +36,29 @@ class Frontend : public Thread { private: - MessageList m_RemoteMessages; + MessageList m_remoteMessages; bool RequestMessages(); bool RequestFileList(); protected: - bool m_bSummary; - bool m_bFileList; - unsigned int m_iNeededLogEntries; - unsigned int m_iNeededLogFirstID; - int m_iUpdateInterval; + bool m_summary; + bool m_fileList; + unsigned int m_neededLogEntries; + unsigned int m_neededLogFirstId; + int m_updateInterval; // summary - int m_iCurrentDownloadSpeed; - long long m_lRemainingSize; - bool m_bPauseDownload; - int m_iDownloadLimit; - int m_iThreadCount; - int m_iPostJobCount; - int m_iUpTimeSec; - int m_iDnTimeSec; - long long m_iAllBytes; - bool m_bStandBy; + int m_currentDownloadSpeed; + long long m_remainingSize; + bool m_pauseDownload; + int m_downloadLimit; + int m_threadCount; + int m_postJobCount; + int m_upTimeSec; + int m_dnTimeSec; + long long m_allBytes; + bool m_standBy; bool PrepareData(); void FreeData(); @@ -67,13 +67,13 @@ protected: DownloadQueue* LockQueue(); void UnlockQueue(); bool IsRemoteMode(); - void InitMessageBase(SNZBRequestBase* pMessageBase, int iRequest, int iSize); - void ServerPauseUnpause(bool bPause); - bool RequestPauseUnpause(bool bPause); - void ServerSetDownloadRate(int iRate); - bool RequestSetDownloadRate(int iRate); - bool ServerEditQueue(DownloadQueue::EEditAction eAction, int iOffset, int iEntry); - bool RequestEditQueue(DownloadQueue::EEditAction eAction, int iOffset, int iID); + void InitMessageBase(SNZBRequestBase* messageBase, int request, int size); + void ServerPauseUnpause(bool pause); + bool RequestPauseUnpause(bool pause); + void ServerSetDownloadRate(int rate); + bool RequestSetDownloadRate(int rate); + bool ServerEditQueue(DownloadQueue::EEditAction action, int offset, int entry); + bool RequestEditQueue(DownloadQueue::EEditAction action, int offset, int id); public: Frontend(); diff --git a/daemon/frontend/LoggableFrontend.cpp b/daemon/frontend/LoggableFrontend.cpp index 352da684..75bb7914 100644 --- a/daemon/frontend/LoggableFrontend.cpp +++ b/daemon/frontend/LoggableFrontend.cpp @@ -47,9 +47,9 @@ LoggableFrontend::LoggableFrontend() { debug("Creating LoggableFrontend"); - m_iNeededLogEntries = 0; - m_bSummary = false; - m_bFileList = false; + m_neededLogEntries = 0; + m_summary = false; + m_fileList = false; } void LoggableFrontend::Run() @@ -59,7 +59,7 @@ void LoggableFrontend::Run() while (!IsStopped()) { Update(); - usleep(m_iUpdateInterval * 1000); + usleep(m_updateInterval * 1000); } // Printing the last messages Update(); @@ -79,20 +79,20 @@ void LoggableFrontend::Update() BeforePrint(); - MessageList* pMessages = LockMessages(); - if (!pMessages->empty()) + MessageList* messages = LockMessages(); + if (!messages->empty()) { - Message* pFirstMessage = pMessages->front(); - int iStart = m_iNeededLogFirstID - pFirstMessage->GetID() + 1; - if (iStart < 0) + Message* firstMessage = messages->front(); + int start = m_neededLogFirstId - firstMessage->GetID() + 1; + if (start < 0) { PrintSkip(); - iStart = 0; + start = 0; } - for (unsigned int i = (unsigned int)iStart; i < pMessages->size(); i++) + for (unsigned int i = (unsigned int)start; i < messages->size(); i++) { - PrintMessage((*pMessages)[i]); - m_iNeededLogFirstID = (*pMessages)[i]->GetID(); + PrintMessage((*messages)[i]); + m_neededLogFirstId = (*messages)[i]->GetID(); } } UnlockMessages(); @@ -104,15 +104,15 @@ void LoggableFrontend::Update() fflush(stdout); } -void LoggableFrontend::PrintMessage(Message * pMessage) +void LoggableFrontend::PrintMessage(Message * message) { #ifdef WIN32 - char* msg = strdup(pMessage->GetText()); + char* msg = strdup(message->GetText()); CharToOem(msg, msg); #else - const char* msg = pMessage->GetText(); + const char* msg = message->GetText(); #endif - switch (pMessage->GetKind()) + switch (message->GetKind()) { case Message::mkDebug: printf("[DEBUG] %s\n", msg); diff --git a/daemon/frontend/LoggableFrontend.h b/daemon/frontend/LoggableFrontend.h index fca64f82..521cb48f 100644 --- a/daemon/frontend/LoggableFrontend.h +++ b/daemon/frontend/LoggableFrontend.h @@ -38,7 +38,7 @@ protected: virtual void Update(); virtual void BeforePrint() {}; virtual void BeforeExit() {}; - virtual void PrintMessage(Message* pMessage); + virtual void PrintMessage(Message* message); virtual void PrintStatus() {}; virtual void PrintSkip(); public: diff --git a/daemon/frontend/NCursesFrontend.cpp b/daemon/frontend/NCursesFrontend.cpp index 912fff3d..f75c078d 100644 --- a/daemon/frontend/NCursesFrontend.cpp +++ b/daemon/frontend/NCursesFrontend.cpp @@ -118,37 +118,37 @@ static const int READKEY_EMPTY = ERR; NCursesFrontend::NCursesFrontend() { - m_iScreenHeight = 0; - m_iScreenWidth = 0; - m_iInputNumberIndex = 0; - m_eInputMode = eNormal; - m_bSummary = true; - m_bFileList = true; - m_iNeededLogEntries = 0; - m_iQueueWinTop = 0; - m_iQueueWinHeight = 0; - m_iQueueWinClientHeight = 0; - m_iMessagesWinTop = 0; - m_iMessagesWinHeight = 0; - m_iMessagesWinClientHeight = 0; - m_iSelectedQueueEntry = 0; - m_iQueueScrollOffset = 0; - m_bShowNZBname = g_pOptions->GetCursesNZBName(); - m_bShowTimestamp = g_pOptions->GetCursesTime(); - m_bGroupFiles = g_pOptions->GetCursesGroup(); - m_QueueWindowPercentage = 50; - m_iDataUpdatePos = 0; - m_bUpdateNextTime = false; - m_iLastEditEntry = -1; - m_bLastPausePars = false; - m_szHint = NULL; + m_screenHeight = 0; + m_screenWidth = 0; + m_inputNumberIndex = 0; + m_inputMode = normal; + m_summary = true; + m_fileList = true; + m_neededLogEntries = 0; + m_queueWinTop = 0; + m_queueWinHeight = 0; + m_queueWinClientHeight = 0; + m_messagesWinTop = 0; + m_messagesWinHeight = 0; + m_messagesWinClientHeight = 0; + m_selectedQueueEntry = 0; + m_queueScrollOffset = 0; + m_showNzbname = g_pOptions->GetCursesNZBName(); + m_showTimestamp = g_pOptions->GetCursesTime(); + m_groupFiles = g_pOptions->GetCursesGroup(); + m_queueWindowPercentage = 50; + m_dataUpdatePos = 0; + m_updateNextTime = false; + m_lastEditEntry = -1; + m_lastPausePars = false; + m_hint = NULL; // Setup curses #ifdef WIN32 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - m_pScreenBuffer = NULL; - m_pOldScreenBuffer = NULL; - m_ColorAttr.clear(); + m_screenBuffer = NULL; + m_oldScreenBuffer = NULL; + m_colorAttr.clear(); CONSOLE_CURSOR_INFO ConsoleCursorInfo; GetConsoleCursorInfo(hConsole, &ConsoleCursorInfo); @@ -163,22 +163,22 @@ NCursesFrontend::NCursesFrontend() SetConsoleTitle("NZBGet"); } - m_bUseColor = true; + m_useColor = true; #else - m_pWindow = initscr(); - if (m_pWindow == NULL) + m_window = initscr(); + if (m_window == NULL) { printf("ERROR: m_pWindow == NULL\n"); exit(-1); } keypad(stdscr, true); - nodelay((WINDOW*)m_pWindow, true); + nodelay((WINDOW*)m_window, true); noecho(); curs_set(0); - m_bUseColor = has_colors(); + m_useColor = has_colors(); #endif - if (m_bUseColor) + if (m_useColor) { #ifndef WIN32 start_color(); @@ -202,10 +202,10 @@ NCursesFrontend::NCursesFrontend() NCursesFrontend::~NCursesFrontend() { #ifdef WIN32 - free(m_pScreenBuffer); - free(m_pOldScreenBuffer); + free(m_screenBuffer); + free(m_oldScreenBuffer); - m_ColorAttr.clear(); + m_colorAttr.clear(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO ConsoleCursorInfo; @@ -226,7 +226,7 @@ void NCursesFrontend::Run() { debug("Entering NCursesFrontend-loop"); - m_iDataUpdatePos = 0; + m_dataUpdatePos = 0; while (!IsStopped()) { @@ -234,38 +234,38 @@ void NCursesFrontend::Run() // but the window is updated more often for better reaction on user's input bool updateNow = false; - int iKey = ReadConsoleKey(); + int key = ReadConsoleKey(); - if (iKey != READKEY_EMPTY) + if (key != READKEY_EMPTY) { // Update now and next if a key is pressed. updateNow = true; - m_bUpdateNextTime = true; + m_updateNextTime = true; } - else if (m_bUpdateNextTime) + else if (m_updateNextTime) { // Update due to key being pressed during previous call. updateNow = true; - m_bUpdateNextTime = false; + m_updateNextTime = false; } - else if (m_iDataUpdatePos <= 0) + else if (m_dataUpdatePos <= 0) { updateNow = true; - m_bUpdateNextTime = false; + m_updateNextTime = false; } if (updateNow) { - Update(iKey); + Update(key); } - if (m_iDataUpdatePos <= 0) + if (m_dataUpdatePos <= 0) { - m_iDataUpdatePos = m_iUpdateInterval; + m_dataUpdatePos = m_updateInterval; } usleep(10 * 1000); - m_iDataUpdatePos -= 10; + m_dataUpdatePos -= 10; } FreeData(); @@ -275,19 +275,19 @@ void NCursesFrontend::Run() void NCursesFrontend::NeedUpdateData() { - m_iDataUpdatePos = 10; - m_bUpdateNextTime = true; + m_dataUpdatePos = 10; + m_updateNextTime = true; } -void NCursesFrontend::Update(int iKey) +void NCursesFrontend::Update(int key) { // Figure out how big the screen is CalcWindowSizes(); - if (m_iDataUpdatePos <= 0) + if (m_dataUpdatePos <= 0) { FreeData(); - m_iNeededLogEntries = m_iMessagesWinClientHeight; + m_neededLogEntries = m_messagesWinClientHeight; if (!PrepareData()) { return; @@ -297,20 +297,20 @@ void NCursesFrontend::Update(int iKey) CalcWindowSizes(); } - if (m_eInputMode == eEditQueue) + if (m_inputMode == editQueue) { - int iQueueSize = CalcQueueSize(); - if (iQueueSize == 0) + int queueSize = CalcQueueSize(); + if (queueSize == 0) { - m_iSelectedQueueEntry = 0; - m_eInputMode = eNormal; + m_selectedQueueEntry = 0; + m_inputMode = normal; } } //------------------------------------------ // Print Current NZBInfoList //------------------------------------------ - if (m_iQueueWinHeight > 0) + if (m_queueWinHeight > 0) { PrintQueue(); } @@ -318,7 +318,7 @@ void NCursesFrontend::Update(int iKey) //------------------------------------------ // Print Messages //------------------------------------------ - if (m_iMessagesWinHeight > 0) + if (m_messagesWinHeight > 0) { PrintMessages(); } @@ -327,121 +327,121 @@ void NCursesFrontend::Update(int iKey) PrintKeyInputBar(); - UpdateInput(iKey); + UpdateInput(key); RefreshScreen(); } void NCursesFrontend::CalcWindowSizes() { - int iNrRows, iNrColumns; + int nrRows, nrColumns; #ifdef WIN32 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO BufInfo; GetConsoleScreenBufferInfo(hConsole, &BufInfo); - iNrRows = BufInfo.srWindow.Bottom - BufInfo.srWindow.Top + 1; - iNrColumns = BufInfo.srWindow.Right - BufInfo.srWindow.Left + 1; + nrRows = BufInfo.srWindow.Bottom - BufInfo.srWindow.Top + 1; + nrColumns = BufInfo.srWindow.Right - BufInfo.srWindow.Left + 1; #else - getmaxyx(stdscr, iNrRows, iNrColumns); + getmaxyx(stdscr, nrRows, nrColumns); #endif - if (iNrRows != m_iScreenHeight || iNrColumns != m_iScreenWidth) + if (nrRows != m_screenHeight || nrColumns != m_screenWidth) { #ifdef WIN32 - m_iScreenBufferSize = iNrRows * iNrColumns * sizeof(CHAR_INFO); - m_pScreenBuffer = (CHAR_INFO*)realloc(m_pScreenBuffer, m_iScreenBufferSize); - memset(m_pScreenBuffer, 0, m_iScreenBufferSize); - m_pOldScreenBuffer = (CHAR_INFO*)realloc(m_pOldScreenBuffer, m_iScreenBufferSize); - memset(m_pOldScreenBuffer, 0, m_iScreenBufferSize); + m_screenBufferSize = nrRows * nrColumns * sizeof(CHAR_INFO); + m_screenBuffer = (CHAR_INFO*)realloc(m_screenBuffer, m_screenBufferSize); + memset(m_screenBuffer, 0, m_screenBufferSize); + m_oldScreenBuffer = (CHAR_INFO*)realloc(m_oldScreenBuffer, m_screenBufferSize); + memset(m_oldScreenBuffer, 0, m_screenBufferSize); #else curses_clear(); #endif - m_iScreenHeight = iNrRows; - m_iScreenWidth = iNrColumns; + m_screenHeight = nrRows; + m_screenWidth = nrColumns; } - int iQueueSize = CalcQueueSize(); + int queueSize = CalcQueueSize(); - m_iQueueWinTop = 0; - m_iQueueWinHeight = (m_iScreenHeight - 2) * m_QueueWindowPercentage / 100; - if (m_iQueueWinHeight - 1 > iQueueSize) + m_queueWinTop = 0; + m_queueWinHeight = (m_screenHeight - 2) * m_queueWindowPercentage / 100; + if (m_queueWinHeight - 1 > queueSize) { - m_iQueueWinHeight = iQueueSize > 0 ? iQueueSize + 1 : 1 + 1; + m_queueWinHeight = queueSize > 0 ? queueSize + 1 : 1 + 1; } - m_iQueueWinClientHeight = m_iQueueWinHeight - 1; - if (m_iQueueWinClientHeight < 0) + m_queueWinClientHeight = m_queueWinHeight - 1; + if (m_queueWinClientHeight < 0) { - m_iQueueWinClientHeight = 0; + m_queueWinClientHeight = 0; } - m_iMessagesWinTop = m_iQueueWinTop + m_iQueueWinHeight; - m_iMessagesWinHeight = m_iScreenHeight - m_iQueueWinHeight - 2; - m_iMessagesWinClientHeight = m_iMessagesWinHeight - 1; - if (m_iMessagesWinClientHeight < 0) + m_messagesWinTop = m_queueWinTop + m_queueWinHeight; + m_messagesWinHeight = m_screenHeight - m_queueWinHeight - 2; + m_messagesWinClientHeight = m_messagesWinHeight - 1; + if (m_messagesWinClientHeight < 0) { - m_iMessagesWinClientHeight = 0; + m_messagesWinClientHeight = 0; } } int NCursesFrontend::CalcQueueSize() { - int iQueueSize = 0; - DownloadQueue* pDownloadQueue = LockQueue(); - if (m_bGroupFiles) + int queueSize = 0; + DownloadQueue* downloadQueue = LockQueue(); + if (m_groupFiles) { - iQueueSize = pDownloadQueue->GetQueue()->size(); + queueSize = downloadQueue->GetQueue()->size(); } else { - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - iQueueSize += pNZBInfo->GetFileList()->size(); + NZBInfo* nzbInfo = *it; + queueSize += nzbInfo->GetFileList()->size(); } } UnlockQueue(); - return iQueueSize; + return queueSize; } -void NCursesFrontend::PlotLine(const char * szString, int iRow, int iPos, int iColorPair) +void NCursesFrontend::PlotLine(const char * string, int row, int pos, int colorPair) { - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, sizeof(szBuffer), "%-*s", m_iScreenWidth, szString); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; - int iLen = strlen(szBuffer); - if (iLen > m_iScreenWidth - iPos && m_iScreenWidth - iPos < MAX_SCREEN_WIDTH) + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), "%-*s", m_screenWidth, string); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; + int len = strlen(buffer); + if (len > m_screenWidth - pos && m_screenWidth - pos < MAX_SCREEN_WIDTH) { - szBuffer[m_iScreenWidth - iPos] = '\0'; + buffer[m_screenWidth - pos] = '\0'; } - PlotText(szBuffer, iRow, iPos, iColorPair, false); + PlotText(buffer, row, pos, colorPair, false); } -void NCursesFrontend::PlotText(const char * szString, int iRow, int iPos, int iColorPair, bool bBlink) +void NCursesFrontend::PlotText(const char * string, int row, int pos, int colorPair, bool blink) { #ifdef WIN32 - int iBufPos = iRow * m_iScreenWidth + iPos; - int len = strlen(szString); + int bufPos = row * m_screenWidth + pos; + int len = strlen(string); for (int i = 0; i < len; i++) { - char c = szString[i]; + char c = string[i]; CharToOemBuff(&c, &c, 1); - m_pScreenBuffer[iBufPos + i].Char.AsciiChar = c; - m_pScreenBuffer[iBufPos + i].Attributes = m_ColorAttr[iColorPair]; + m_screenBuffer[bufPos + i].Char.AsciiChar = c; + m_screenBuffer[bufPos + i].Attributes = m_colorAttr[colorPair]; } #else - if( m_bUseColor ) + if( m_useColor ) { - attron(COLOR_PAIR(iColorPair)); - if (bBlink) + attron(COLOR_PAIR(colorPair)); + if (blink) { attron(A_BLINK); } } - mvaddstr(iRow, iPos, (char*)szString); - if( m_bUseColor ) + mvaddstr(row, pos, (char*)string); + if( m_useColor ) { - attroff(COLOR_PAIR(iColorPair)); - if (bBlink) + attroff(COLOR_PAIR(colorPair)); + if (blink) { attroff(A_BLINK); } @@ -452,12 +452,12 @@ void NCursesFrontend::PlotText(const char * szString, int iRow, int iPos, int iC void NCursesFrontend::RefreshScreen() { #ifdef WIN32 - bool bBufChanged = memcmp(m_pScreenBuffer, m_pOldScreenBuffer, m_iScreenBufferSize); - if (bBufChanged) + bool bufChanged = memcmp(m_screenBuffer, m_oldScreenBuffer, m_screenBufferSize); + if (bufChanged) { COORD BufSize; - BufSize.X = m_iScreenWidth; - BufSize.Y = m_iScreenHeight; + BufSize.X = m_screenWidth; + BufSize.Y = m_screenHeight; COORD BufCoord; BufCoord.X = 0; @@ -466,17 +466,17 @@ void NCursesFrontend::RefreshScreen() HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO BufInfo; GetConsoleScreenBufferInfo(hConsole, &BufInfo); - WriteConsoleOutput(hConsole, m_pScreenBuffer, BufSize, BufCoord, &BufInfo.srWindow); + WriteConsoleOutput(hConsole, m_screenBuffer, BufSize, BufCoord, &BufInfo.srWindow); BufInfo.dwCursorPosition.X = BufInfo.srWindow.Right; BufInfo.dwCursorPosition.Y = BufInfo.srWindow.Bottom; SetConsoleCursorPosition(hConsole, BufInfo.dwCursorPosition); - memcpy(m_pOldScreenBuffer, m_pScreenBuffer, m_iScreenBufferSize); + memcpy(m_oldScreenBuffer, m_screenBuffer, m_screenBufferSize); } #else // Cursor placement - wmove((WINDOW*)m_pWindow, m_iScreenHeight, m_iScreenWidth); + wmove((WINDOW*)m_window, m_screenHeight, m_screenWidth); // NCurses refresh refresh(); @@ -484,90 +484,90 @@ void NCursesFrontend::RefreshScreen() } #ifdef WIN32 -void NCursesFrontend::init_pair(int iColorNumber, WORD wForeColor, WORD wBackColor) +void NCursesFrontend::init_pair(int colorNumber, WORD wForeColor, WORD wBackColor) { - m_ColorAttr.resize(iColorNumber + 1); - m_ColorAttr[iColorNumber] = wForeColor | (wBackColor << 4); + m_colorAttr.resize(colorNumber + 1); + m_colorAttr[colorNumber] = wForeColor | (wBackColor << 4); } #endif void NCursesFrontend::PrintMessages() { - int iLineNr = m_iMessagesWinTop; + int lineNr = m_messagesWinTop; - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, sizeof(szBuffer), "%s Messages", m_bUseColor ? "" : "*** "); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; - PlotLine(szBuffer, iLineNr++, 0, NCURSES_COLORPAIR_INFOLINE); + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), "%s Messages", m_useColor ? "" : "*** "); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; + PlotLine(buffer, lineNr++, 0, NCURSES_COLORPAIR_INFOLINE); - int iLine = iLineNr + m_iMessagesWinClientHeight - 1; - int iLinesToPrint = m_iMessagesWinClientHeight; + int line = lineNr + m_messagesWinClientHeight - 1; + int linesToPrint = m_messagesWinClientHeight; - MessageList* pMessages = LockMessages(); + MessageList* messages = LockMessages(); // print messages from bottom - for (int i = (int)pMessages->size() - 1; i >= 0 && iLinesToPrint > 0; i--) + for (int i = (int)messages->size() - 1; i >= 0 && linesToPrint > 0; i--) { - int iPrintedLines = PrintMessage((*pMessages)[i], iLine, iLinesToPrint); - iLine -= iPrintedLines; - iLinesToPrint -= iPrintedLines; + int printedLines = PrintMessage((*messages)[i], line, linesToPrint); + line -= printedLines; + linesToPrint -= printedLines; } - if (iLinesToPrint > 0) + if (linesToPrint > 0) { // too few messages, print them again from top - iLine = iLineNr + m_iMessagesWinClientHeight - 1; - while (iLinesToPrint-- > 0) + line = lineNr + m_messagesWinClientHeight - 1; + while (linesToPrint-- > 0) { - PlotLine("", iLine--, 0, NCURSES_COLORPAIR_TEXT); + PlotLine("", line--, 0, NCURSES_COLORPAIR_TEXT); } - int iLinesToPrint2 = m_iMessagesWinClientHeight; - for (int i = (int)pMessages->size() - 1; i >= 0 && iLinesToPrint2 > 0; i--) + int linesToPrint2 = m_messagesWinClientHeight; + for (int i = (int)messages->size() - 1; i >= 0 && linesToPrint2 > 0; i--) { - int iPrintedLines = PrintMessage((*pMessages)[i], iLine, iLinesToPrint2); - iLine -= iPrintedLines; - iLinesToPrint2 -= iPrintedLines; + int printedLines = PrintMessage((*messages)[i], line, linesToPrint2); + line -= printedLines; + linesToPrint2 -= printedLines; } } UnlockMessages(); } -int NCursesFrontend::PrintMessage(Message* Msg, int iRow, int iMaxLines) +int NCursesFrontend::PrintMessage(Message* Msg, int row, int maxLines) { - const char* szMessageType[] = { "INFO ", "WARNING ", "ERROR ", "DEBUG ", "DETAIL "}; - const int iMessageTypeColor[] = { NCURSES_COLORPAIR_INFO, NCURSES_COLORPAIR_WARNING, + const char* messageType[] = { "INFO ", "WARNING ", "ERROR ", "DEBUG ", "DETAIL "}; + const int messageTypeColor[] = { NCURSES_COLORPAIR_INFO, NCURSES_COLORPAIR_WARNING, NCURSES_COLORPAIR_ERROR, NCURSES_COLORPAIR_DEBUG, NCURSES_COLORPAIR_DETAIL }; - char* szText = (char*)Msg->GetText(); + char* text = (char*)Msg->GetText(); - if (m_bShowTimestamp) + if (m_showTimestamp) { - int iLen = strlen(szText) + 50; - szText = (char*)malloc(iLen); + int len = strlen(text) + 50; + text = (char*)malloc(len); time_t rawtime = Msg->GetTime(); rawtime += g_pOptions->GetTimeCorrection(); - char szTime[50]; + char time[50]; #ifdef HAVE_CTIME_R_3 - ctime_r(&rawtime, szTime, 50); + ctime_r(&rawtime, time, 50); #else - ctime_r(&rawtime, szTime); + ctime_r(&rawtime, time); #endif - szTime[50-1] = '\0'; - szTime[strlen(szTime) - 1] = '\0'; // trim LF + time[50-1] = '\0'; + time[strlen(time) - 1] = '\0'; // trim LF - snprintf(szText, iLen, "%s - %s", szTime, Msg->GetText()); - szText[iLen - 1] = '\0'; + snprintf(text, len, "%s - %s", time, Msg->GetText()); + text[len - 1] = '\0'; } else { - szText = strdup(szText); + text = strdup(text); } // replace some special characters with spaces - for (char* p = szText; *p; p++) + for (char* p = text; *p; p++) { if (*p == '\n' || *p == '\r' || *p == '\b') { @@ -575,98 +575,98 @@ int NCursesFrontend::PrintMessage(Message* Msg, int iRow, int iMaxLines) } } - int iLen = strlen(szText); - int iWinWidth = m_iScreenWidth - 8; - int iMsgLines = iLen / iWinWidth; - if (iLen % iWinWidth > 0) + int len = strlen(text); + int winWidth = m_screenWidth - 8; + int msgLines = len / winWidth; + if (len % winWidth > 0) { - iMsgLines++; + msgLines++; } - int iLines = 0; - for (int i = iMsgLines - 1; i >= 0 && iLines < iMaxLines; i--) + int lines = 0; + for (int i = msgLines - 1; i >= 0 && lines < maxLines; i--) { - int iR = iRow - iMsgLines + i + 1; - PlotLine(szText + iWinWidth * i, iR, 8, NCURSES_COLORPAIR_TEXT); + int r = row - msgLines + i + 1; + PlotLine(text + winWidth * i, r, 8, NCURSES_COLORPAIR_TEXT); if (i == 0) { - PlotText(szMessageType[Msg->GetKind()], iR, 0, iMessageTypeColor[Msg->GetKind()], false); + PlotText(messageType[Msg->GetKind()], r, 0, messageTypeColor[Msg->GetKind()], false); } else { - PlotText(" ", iR, 0, iMessageTypeColor[Msg->GetKind()], false); + PlotText(" ", r, 0, messageTypeColor[Msg->GetKind()], false); } - iLines++; + lines++; } - free(szText); + free(text); - return iLines; + return lines; } void NCursesFrontend::PrintStatus() { char tmp[MAX_SCREEN_WIDTH]; - int iStatusRow = m_iScreenHeight - 2; + int statusRow = m_screenHeight - 2; char timeString[100]; timeString[0] = '\0'; - int iCurrentDownloadSpeed = m_bStandBy ? 0 : m_iCurrentDownloadSpeed; - if (iCurrentDownloadSpeed > 0 && !m_bPauseDownload) + int currentDownloadSpeed = m_standBy ? 0 : m_currentDownloadSpeed; + if (currentDownloadSpeed > 0 && !m_pauseDownload) { - long long remain_sec = (long long)(m_lRemainingSize / iCurrentDownloadSpeed); + long long remain_sec = (long long)(m_remainingSize / currentDownloadSpeed); int h = (int)(remain_sec / 3600); int m = (int)((remain_sec % 3600) / 60); int s = (int)(remain_sec % 60); sprintf(timeString, " (~ %.2d:%.2d:%.2d)", h, m, s); } - char szDownloadLimit[128]; - if (m_iDownloadLimit > 0) + char downloadLimit[128]; + if (m_downloadLimit > 0) { - sprintf(szDownloadLimit, ", Limit %i KB/s", m_iDownloadLimit / 1024); + sprintf(downloadLimit, ", Limit %i KB/s", m_downloadLimit / 1024); } else { - szDownloadLimit[0] = 0; + downloadLimit[0] = 0; } - char szPostStatus[128]; - if (m_iPostJobCount > 0) + char postStatus[128]; + if (m_postJobCount > 0) { - sprintf(szPostStatus, ", %i post-job%s", m_iPostJobCount, m_iPostJobCount > 1 ? "s" : ""); + sprintf(postStatus, ", %i post-job%s", m_postJobCount, m_postJobCount > 1 ? "s" : ""); } else { - szPostStatus[0] = 0; + postStatus[0] = 0; } - char szCurrentSpeed[20]; - char szAverageSpeed[20]; - char szRemainingSize[20]; - int iAverageSpeed = (int)(m_iDnTimeSec > 0 ? m_iAllBytes / m_iDnTimeSec : 0); + char currentSpeedBuf[20]; + char averageSpeedBuf[20]; + char remainingSizeBuf[20]; + int averageSpeed = (int)(m_dnTimeSec > 0 ? m_allBytes / m_dnTimeSec : 0); snprintf(tmp, MAX_SCREEN_WIDTH, " %d threads, %s, %s remaining%s%s%s%s, Avg. %s", - m_iThreadCount, Util::FormatSpeed(szCurrentSpeed, sizeof(szCurrentSpeed), iCurrentDownloadSpeed), - Util::FormatSize(szRemainingSize, sizeof(szRemainingSize), m_lRemainingSize), - timeString, szPostStatus, m_bPauseDownload ? (m_bStandBy ? ", Paused" : ", Pausing") : "", - szDownloadLimit, Util::FormatSpeed(szAverageSpeed, sizeof(szAverageSpeed), iAverageSpeed)); + m_threadCount, Util::FormatSpeed(currentSpeedBuf, sizeof(currentSpeedBuf), currentDownloadSpeed), + Util::FormatSize(remainingSizeBuf, sizeof(remainingSizeBuf), m_remainingSize), + timeString, postStatus, m_pauseDownload ? (m_standBy ? ", Paused" : ", Pausing") : "", + downloadLimit, Util::FormatSpeed(averageSpeedBuf, sizeof(averageSpeedBuf), averageSpeed)); tmp[MAX_SCREEN_WIDTH - 1] = '\0'; - PlotLine(tmp, iStatusRow, 0, NCURSES_COLORPAIR_STATUS); + PlotLine(tmp, statusRow, 0, NCURSES_COLORPAIR_STATUS); } void NCursesFrontend::PrintKeyInputBar() { - int iQueueSize = CalcQueueSize(); - int iInputBarRow = m_iScreenHeight - 1; + int queueSize = CalcQueueSize(); + int inputBarRow = m_screenHeight - 1; - if (m_szHint) + if (m_hint) { - time_t tTime = time(NULL); - if (tTime - m_tStartHint < 5) + time_t time = ::time(NULL); + if (time - m_startHint < 5) { - PlotLine(m_szHint, iInputBarRow, 0, NCURSES_COLORPAIR_HINT); + PlotLine(m_hint, inputBarRow, 0, NCURSES_COLORPAIR_HINT); return; } else @@ -675,66 +675,66 @@ void NCursesFrontend::PrintKeyInputBar() } } - switch (m_eInputMode) + switch (m_inputMode) { - case eNormal: - if (m_bGroupFiles) + case normal: + if (m_groupFiles) { - PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime", iInputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); + PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime", inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); } else { - PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime | n(Z)b", iInputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); + PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime | n(Z)b", inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); } break; - case eEditQueue: + case editQueue: { - const char* szStatus = NULL; - if (m_iSelectedQueueEntry > 0 && iQueueSize > 1 && m_iSelectedQueueEntry == iQueueSize - 1) + const char* status = NULL; + if (m_selectedQueueEntry > 0 && queueSize > 1 && m_selectedQueueEntry == queueSize - 1) { - szStatus = "(Q)uit | (E)xit | (P)ause | (D)elete | (U)p/(T)op"; + status = "(Q)uit | (E)xit | (P)ause | (D)elete | (U)p/(T)op"; } - else if (iQueueSize > 1 && m_iSelectedQueueEntry == 0) + else if (queueSize > 1 && m_selectedQueueEntry == 0) { - szStatus = "(Q)uit | (E)xit | (P)ause | (D)elete | dow(N)/(B)ottom"; + status = "(Q)uit | (E)xit | (P)ause | (D)elete | dow(N)/(B)ottom"; } - else if (iQueueSize > 1) + else if (queueSize > 1) { - szStatus = "(Q)uit | (E)xit | (P)ause | (D)elete | (U)p/dow(N)/(T)op/(B)ottom"; + status = "(Q)uit | (E)xit | (P)ause | (D)elete | (U)p/dow(N)/(T)op/(B)ottom"; } else { - szStatus = "(Q)uit | (E)xit | (P)ause | (D)elete"; + status = "(Q)uit | (E)xit | (P)ause | (D)elete"; } - PlotLine(szStatus, iInputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); + PlotLine(status, inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); break; } - case eDownloadRate: - char szString[128]; - snprintf(szString, 128, "Download rate: %i", m_iInputValue); - szString[128-1] = '\0'; - PlotLine(szString, iInputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); + case downloadRate: + char string[128]; + snprintf(string, 128, "Download rate: %i", m_inputValue); + string[128-1] = '\0'; + PlotLine(string, inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); // Print the cursor - PlotText(" ", iInputBarRow, 15 + m_iInputNumberIndex, NCURSES_COLORPAIR_CURSOR, true); + PlotText(" ", inputBarRow, 15 + m_inputNumberIndex, NCURSES_COLORPAIR_CURSOR, true); break; } } -void NCursesFrontend::SetHint(const char* szHint) +void NCursesFrontend::SetHint(const char* hint) { - free(m_szHint); - m_szHint = NULL; - if (szHint) + free(m_hint); + m_hint = NULL; + if (hint) { - m_szHint = strdup(szHint); - m_tStartHint = time(NULL); + m_hint = strdup(hint); + m_startHint = time(NULL); } } void NCursesFrontend::PrintQueue() { - if (m_bGroupFiles) + if (m_groupFiles) { PrintGroupQueue(); } @@ -746,70 +746,70 @@ void NCursesFrontend::PrintQueue() void NCursesFrontend::PrintFileQueue() { - DownloadQueue* pDownloadQueue = LockQueue(); + DownloadQueue* downloadQueue = LockQueue(); - int iLineNr = m_iQueueWinTop + 1; - long long lRemaining = 0; - long long lPaused = 0; - int iPausedFiles = 0; - int iFileNum = 0; + int lineNr = m_queueWinTop + 1; + long long remaining = 0; + long long paused = 0; + int pausedFiles = 0; + int fileNum = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++, iFileNum++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++, fileNum++) { - FileInfo* pFileInfo = *it2; + FileInfo* fileInfo = *it2; - if (iFileNum >= m_iQueueScrollOffset && iFileNum < m_iQueueScrollOffset + m_iQueueWinHeight -1) + if (fileNum >= m_queueScrollOffset && fileNum < m_queueScrollOffset + m_queueWinHeight -1) { - PrintFilename(pFileInfo, iLineNr++, iFileNum == m_iSelectedQueueEntry); + PrintFilename(fileInfo, lineNr++, fileNum == m_selectedQueueEntry); } - if (pFileInfo->GetPaused()) + if (fileInfo->GetPaused()) { - iPausedFiles++; - lPaused += pFileInfo->GetRemainingSize(); + pausedFiles++; + paused += fileInfo->GetRemainingSize(); } - lRemaining += pFileInfo->GetRemainingSize(); + remaining += fileInfo->GetRemainingSize(); } } - if (iFileNum > 0) + if (fileNum > 0) { - char szRemaining[20]; - char szUnpaused[20]; - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, sizeof(szBuffer), " %sFiles for downloading - %i / %i files in queue - %s / %s", - m_bUseColor ? "" : "*** ", iFileNum, - iFileNum - iPausedFiles, - Util::FormatSize(szRemaining, sizeof(szRemaining), lRemaining), - Util::FormatSize(szUnpaused, sizeof(szUnpaused), lRemaining - lPaused)); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; - PrintTopHeader(szBuffer, m_iQueueWinTop, true); + char remainingBuf[20]; + char unpausedBuf[20]; + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), " %sFiles for downloading - %i / %i files in queue - %s / %s", + m_useColor ? "" : "*** ", fileNum, + fileNum - pausedFiles, + Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining), + Util::FormatSize(unpausedBuf, sizeof(unpausedBuf), remaining - paused)); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; + PrintTopHeader(buffer, m_queueWinTop, true); } else { - iLineNr--; - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, sizeof(szBuffer), "%s Files for downloading", m_bUseColor ? "" : "*** "); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; - PrintTopHeader(szBuffer, iLineNr++, true); - PlotLine("Ready to receive nzb-job", iLineNr++, 0, NCURSES_COLORPAIR_TEXT); + lineNr--; + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), "%s Files for downloading", m_useColor ? "" : "*** "); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; + PrintTopHeader(buffer, lineNr++, true); + PlotLine("Ready to receive nzb-job", lineNr++, 0, NCURSES_COLORPAIR_TEXT); } UnlockQueue(); } -void NCursesFrontend::PrintFilename(FileInfo * pFileInfo, int iRow, bool bSelected) +void NCursesFrontend::PrintFilename(FileInfo * fileInfo, int row, bool selected) { int color = 0; const char* Brace1 = "["; const char* Brace2 = "]"; - if (m_eInputMode == eEditQueue && bSelected) + if (m_inputMode == editQueue && selected) { color = NCURSES_COLORPAIR_TEXTHIGHL; - if (!m_bUseColor) + if (!m_useColor) { Brace1 = "<"; Brace2 = ">"; @@ -820,321 +820,321 @@ void NCursesFrontend::PrintFilename(FileInfo * pFileInfo, int iRow, bool bSelect color = NCURSES_COLORPAIR_TEXT; } - const char* szDownloading = ""; - if (pFileInfo->GetActiveDownloads() > 0) + const char* downloading = ""; + if (fileInfo->GetActiveDownloads() > 0) { - szDownloading = " *"; + downloading = " *"; } - char szPriority[100]; - szPriority[0] = '\0'; - if (pFileInfo->GetNZBInfo()->GetPriority() != 0) + char priority[100]; + priority[0] = '\0'; + if (fileInfo->GetNZBInfo()->GetPriority() != 0) { - sprintf(szPriority, " [%+i]", pFileInfo->GetNZBInfo()->GetPriority()); + sprintf(priority, " [%+i]", fileInfo->GetNZBInfo()->GetPriority()); } - char szCompleted[20]; - szCompleted[0] = '\0'; - if (pFileInfo->GetRemainingSize() < pFileInfo->GetSize()) + char completed[20]; + completed[0] = '\0'; + if (fileInfo->GetRemainingSize() < fileInfo->GetSize()) { - sprintf(szCompleted, ", %i%%", (int)(100 - pFileInfo->GetRemainingSize() * 100 / pFileInfo->GetSize())); + sprintf(completed, ", %i%%", (int)(100 - fileInfo->GetRemainingSize() * 100 / fileInfo->GetSize())); } - char szNZBNiceName[1024]; - if (m_bShowNZBname) + char nzbNiceName[1024]; + if (m_showNzbname) { - strncpy(szNZBNiceName, pFileInfo->GetNZBInfo()->GetName(), 1023); - int len = strlen(szNZBNiceName); - szNZBNiceName[len] = PATH_SEPARATOR; - szNZBNiceName[len + 1] = '\0'; + strncpy(nzbNiceName, fileInfo->GetNZBInfo()->GetName(), 1023); + int len = strlen(nzbNiceName); + nzbNiceName[len] = PATH_SEPARATOR; + nzbNiceName[len + 1] = '\0'; } else { - szNZBNiceName[0] = '\0'; + nzbNiceName[0] = '\0'; } - char szSize[20]; - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, MAX_SCREEN_WIDTH, "%s%i%s%s%s %s%s (%s%s)%s", Brace1, pFileInfo->GetID(), - Brace2, szPriority, szDownloading, szNZBNiceName, pFileInfo->GetFilename(), - Util::FormatSize(szSize, sizeof(szSize), pFileInfo->GetSize()), - szCompleted, pFileInfo->GetPaused() ? " (paused)" : ""); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; + char size[20]; + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, MAX_SCREEN_WIDTH, "%s%i%s%s%s %s%s (%s%s)%s", Brace1, fileInfo->GetID(), + Brace2, priority, downloading, nzbNiceName, fileInfo->GetFilename(), + Util::FormatSize(size, sizeof(size), fileInfo->GetSize()), + completed, fileInfo->GetPaused() ? " (paused)" : ""); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; - PlotLine(szBuffer, iRow, 0, color); + PlotLine(buffer, row, 0, color); } -void NCursesFrontend::PrintTopHeader(char* szHeader, int iLineNr, bool bUpTime) +void NCursesFrontend::PrintTopHeader(char* header, int lineNr, bool upTime) { - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, sizeof(szBuffer), "%-*s", m_iScreenWidth, szHeader); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; - int iHeaderLen = strlen(szHeader); - int iCharsLeft = m_iScreenWidth - iHeaderLen - 2; + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), "%-*s", m_screenWidth, header); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; + int headerLen = strlen(header); + int charsLeft = m_screenWidth - headerLen - 2; - int iTime = bUpTime ? m_iUpTimeSec : m_iDnTimeSec; - int d = iTime / 3600 / 24; - int h = (iTime % (3600 * 24)) / 3600; - int m = (iTime % 3600) / 60; - int s = iTime % 60; - char szTime[30]; + int time = upTime ? m_upTimeSec : m_dnTimeSec; + int d = time / 3600 / 24; + int h = (time % (3600 * 24)) / 3600; + int m = (time % 3600) / 60; + int s = time % 60; + char timeStr[30]; if (d == 0) { - snprintf(szTime, 30, "%.2d:%.2d:%.2d", h, m, s); - if ((int)strlen(szTime) > iCharsLeft) + snprintf(timeStr, 30, "%.2d:%.2d:%.2d", h, m, s); + if ((int)strlen(timeStr) > charsLeft) { - snprintf(szTime, 30, "%.2d:%.2d", h, m); + snprintf(timeStr, 30, "%.2d:%.2d", h, m); } } else { - snprintf(szTime, 30, "%i %s %.2d:%.2d:%.2d", d, (d == 1 ? "day" : "days"), h, m, s); - if ((int)strlen(szTime) > iCharsLeft) + snprintf(timeStr, 30, "%i %s %.2d:%.2d:%.2d", d, (d == 1 ? "day" : "days"), h, m, s); + if ((int)strlen(timeStr) > charsLeft) { - snprintf(szTime, 30, "%id %.2d:%.2d:%.2d", d, h, m, s); + snprintf(timeStr, 30, "%id %.2d:%.2d:%.2d", d, h, m, s); } - if ((int)strlen(szTime) > iCharsLeft) + if ((int)strlen(timeStr) > charsLeft) { - snprintf(szTime, 30, "%id %.2d:%.2d", d, h, m); + snprintf(timeStr, 30, "%id %.2d:%.2d", d, h, m); } } - szTime[29] = '\0'; - const char* szShortCap = bUpTime ? " Up " : "Dn "; - const char* szLongCap = bUpTime ? " Uptime " : " Download-time "; + timeStr[29] = '\0'; + const char* shortCap = upTime ? " Up " : "Dn "; + const char* longCap = upTime ? " Uptime " : " Download-time "; - int iTimeLen = strlen(szTime); - int iShortCapLen = strlen(szShortCap); - int iLongCapLen = strlen(szLongCap); + int timeLen = strlen(timeStr); + int shortCapLen = strlen(shortCap); + int longCapLen = strlen(longCap); - if (iCharsLeft - iTimeLen - iLongCapLen >= 0) + if (charsLeft - timeLen - longCapLen >= 0) { - snprintf(szBuffer + m_iScreenWidth - iTimeLen - iLongCapLen, MAX_SCREEN_WIDTH - (m_iScreenWidth - iTimeLen - iLongCapLen), "%s%s", szLongCap, szTime); + snprintf(buffer + m_screenWidth - timeLen - longCapLen, MAX_SCREEN_WIDTH - (m_screenWidth - timeLen - longCapLen), "%s%s", longCap, timeStr); } - else if (iCharsLeft - iTimeLen - iShortCapLen >= 0) + else if (charsLeft - timeLen - shortCapLen >= 0) { - snprintf(szBuffer + m_iScreenWidth - iTimeLen - iShortCapLen, MAX_SCREEN_WIDTH - (m_iScreenWidth - iTimeLen - iShortCapLen), "%s%s", szShortCap, szTime); + snprintf(buffer + m_screenWidth - timeLen - shortCapLen, MAX_SCREEN_WIDTH - (m_screenWidth - timeLen - shortCapLen), "%s%s", shortCap, timeStr); } - else if (iCharsLeft - iTimeLen >= 0) + else if (charsLeft - timeLen >= 0) { - snprintf(szBuffer + m_iScreenWidth - iTimeLen, MAX_SCREEN_WIDTH - (m_iScreenWidth - iTimeLen), "%s", szTime); + snprintf(buffer + m_screenWidth - timeLen, MAX_SCREEN_WIDTH - (m_screenWidth - timeLen), "%s", timeStr); } - PlotLine(szBuffer, iLineNr, 0, NCURSES_COLORPAIR_INFOLINE); + PlotLine(buffer, lineNr, 0, NCURSES_COLORPAIR_INFOLINE); } void NCursesFrontend::PrintGroupQueue() { - int iLineNr = m_iQueueWinTop; + int lineNr = m_queueWinTop; - DownloadQueue* pDownloadQueue = LockQueue(); - if (pDownloadQueue->GetQueue()->empty()) + DownloadQueue* downloadQueue = LockQueue(); + if (downloadQueue->GetQueue()->empty()) { - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, sizeof(szBuffer), "%s NZBs for downloading", m_bUseColor ? "" : "*** "); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; - PrintTopHeader(szBuffer, iLineNr++, false); - PlotLine("Ready to receive nzb-job", iLineNr++, 0, NCURSES_COLORPAIR_TEXT); + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), "%s NZBs for downloading", m_useColor ? "" : "*** "); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; + PrintTopHeader(buffer, lineNr++, false); + PlotLine("Ready to receive nzb-job", lineNr++, 0, NCURSES_COLORPAIR_TEXT); } else { - iLineNr++; + lineNr++; ResetColWidths(); - int iCalcLineNr = iLineNr; + int calcLineNr = lineNr; int i = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++, i++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++, i++) { - NZBInfo* pNZBInfo = *it; - if (i >= m_iQueueScrollOffset && i < m_iQueueScrollOffset + m_iQueueWinHeight -1) + NZBInfo* nzbInfo = *it; + if (i >= m_queueScrollOffset && i < m_queueScrollOffset + m_queueWinHeight -1) { - PrintGroupname(pNZBInfo, iCalcLineNr++, false, true); + PrintGroupname(nzbInfo, calcLineNr++, false, true); } } - long long lRemaining = 0; - long long lPaused = 0; + long long remaining = 0; + long long paused = 0; i = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++, i++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++, i++) { - NZBInfo* pNZBInfo = *it; - if (i >= m_iQueueScrollOffset && i < m_iQueueScrollOffset + m_iQueueWinHeight -1) + NZBInfo* nzbInfo = *it; + if (i >= m_queueScrollOffset && i < m_queueScrollOffset + m_queueWinHeight -1) { - PrintGroupname(pNZBInfo, iLineNr++, i == m_iSelectedQueueEntry, false); + PrintGroupname(nzbInfo, lineNr++, i == m_selectedQueueEntry, false); } - lRemaining += pNZBInfo->GetRemainingSize(); - lPaused += pNZBInfo->GetPausedSize(); + remaining += nzbInfo->GetRemainingSize(); + paused += nzbInfo->GetPausedSize(); } - char szRemaining[20]; - Util::FormatSize(szRemaining, sizeof(szRemaining), lRemaining); + char remainingBuf[20]; + Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining); - char szUnpaused[20]; - Util::FormatSize(szUnpaused, sizeof(szUnpaused), lRemaining - lPaused); + char unpausedBuf[20]; + Util::FormatSize(unpausedBuf, sizeof(unpausedBuf), remaining - paused); - char szBuffer[MAX_SCREEN_WIDTH]; - snprintf(szBuffer, sizeof(szBuffer), " %sNZBs for downloading - %i NZBs in queue - %s / %s", - m_bUseColor ? "" : "*** ", (int)pDownloadQueue->GetQueue()->size(), szRemaining, szUnpaused); - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; - PrintTopHeader(szBuffer, m_iQueueWinTop, false); + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), " %sNZBs for downloading - %i NZBs in queue - %s / %s", + m_useColor ? "" : "*** ", (int)downloadQueue->GetQueue()->size(), remainingBuf, unpausedBuf); + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; + PrintTopHeader(buffer, m_queueWinTop, false); } UnlockQueue(); } void NCursesFrontend::ResetColWidths() { - m_iColWidthFiles = 0; - m_iColWidthTotal = 0; - m_iColWidthLeft = 0; + m_colWidthFiles = 0; + m_colWidthTotal = 0; + m_colWidthLeft = 0; } -void NCursesFrontend::PrintGroupname(NZBInfo* pNZBInfo, int iRow, bool bSelected, bool bCalcColWidth) +void NCursesFrontend::PrintGroupname(NZBInfo* nzbInfo, int row, bool selected, bool calcColWidth) { int color = NCURSES_COLORPAIR_TEXT; char chBrace1 = '['; char chBrace2 = ']'; - if (m_eInputMode == eEditQueue && bSelected) + if (m_inputMode == editQueue && selected) { color = NCURSES_COLORPAIR_TEXTHIGHL; - if (!m_bUseColor) + if (!m_useColor) { chBrace1 = '<'; chBrace2 = '>'; } } - const char* szDownloading = ""; - if (pNZBInfo->GetActiveDownloads() > 0) + const char* downloading = ""; + if (nzbInfo->GetActiveDownloads() > 0) { - szDownloading = " *"; + downloading = " *"; } - long long lUnpausedRemainingSize = pNZBInfo->GetRemainingSize() - pNZBInfo->GetPausedSize(); + long long unpausedRemainingSize = nzbInfo->GetRemainingSize() - nzbInfo->GetPausedSize(); - char szRemaining[20]; - Util::FormatSize(szRemaining, sizeof(szRemaining), lUnpausedRemainingSize); + char remaining[20]; + Util::FormatSize(remaining, sizeof(remaining), unpausedRemainingSize); - char szPriority[100]; - szPriority[0] = '\0'; - if (pNZBInfo->GetPriority() != 0) + char priority[100]; + priority[0] = '\0'; + if (nzbInfo->GetPriority() != 0) { - sprintf(szPriority, " [%+i]", pNZBInfo->GetPriority()); + sprintf(priority, " [%+i]", nzbInfo->GetPriority()); } - char szBuffer[MAX_SCREEN_WIDTH]; + char buffer[MAX_SCREEN_WIDTH]; // Format: // [id - id] Name Left-Files/Paused Total Left Time // [1-2] Nzb-name 999/999 999.99 MB 999.99 MB 00:00:00 - int iNameLen = 0; - if (bCalcColWidth) + int nameLen = 0; + if (calcColWidth) { - iNameLen = m_iScreenWidth - 1 - 9 - 11 - 11 - 9; + nameLen = m_screenWidth - 1 - 9 - 11 - 11 - 9; } else { - iNameLen = m_iScreenWidth - 1 - m_iColWidthFiles - 2 - m_iColWidthTotal - 2 - m_iColWidthLeft - 2 - 9; + nameLen = m_screenWidth - 1 - m_colWidthFiles - 2 - m_colWidthTotal - 2 - m_colWidthLeft - 2 - 9; } - bool bPrintFormatted = iNameLen > 20; + bool printFormatted = nameLen > 20; - if (bPrintFormatted) + if (printFormatted) { - char szFiles[20]; - snprintf(szFiles, 20, "%i/%i", (int)pNZBInfo->GetFileList()->size(), pNZBInfo->GetPausedFileCount()); - szFiles[20-1] = '\0'; + char files[20]; + snprintf(files, 20, "%i/%i", (int)nzbInfo->GetFileList()->size(), nzbInfo->GetPausedFileCount()); + files[20-1] = '\0'; - char szTotal[20]; - Util::FormatSize(szTotal, sizeof(szTotal), pNZBInfo->GetSize()); + char total[20]; + Util::FormatSize(total, sizeof(total), nzbInfo->GetSize()); - char szNameWithIds[1024]; - snprintf(szNameWithIds, 1024, "%c%i%c%s%s %s", chBrace1, pNZBInfo->GetID(), chBrace2, - szPriority, szDownloading, pNZBInfo->GetName()); - szNameWithIds[iNameLen] = '\0'; + char nameWithIds[1024]; + snprintf(nameWithIds, 1024, "%c%i%c%s%s %s", chBrace1, nzbInfo->GetID(), chBrace2, + priority, downloading, nzbInfo->GetName()); + nameWithIds[nameLen] = '\0'; - char szTime[100]; - szTime[0] = '\0'; - int iCurrentDownloadSpeed = m_bStandBy ? 0 : m_iCurrentDownloadSpeed; - if (pNZBInfo->GetPausedSize() > 0 && lUnpausedRemainingSize == 0) + char time[100]; + time[0] = '\0'; + int currentDownloadSpeed = m_standBy ? 0 : m_currentDownloadSpeed; + if (nzbInfo->GetPausedSize() > 0 && unpausedRemainingSize == 0) { - snprintf(szTime, 100, "[paused]"); - Util::FormatSize(szRemaining, sizeof(szRemaining), pNZBInfo->GetRemainingSize()); + snprintf(time, 100, "[paused]"); + Util::FormatSize(remaining, sizeof(remaining), nzbInfo->GetRemainingSize()); } - else if (iCurrentDownloadSpeed > 0 && !m_bPauseDownload) + else if (currentDownloadSpeed > 0 && !m_pauseDownload) { - long long remain_sec = (long long)(lUnpausedRemainingSize / iCurrentDownloadSpeed); + long long remain_sec = (long long)(unpausedRemainingSize / currentDownloadSpeed); int h = (int)(remain_sec / 3600); int m = (int)((remain_sec % 3600) / 60); int s = (int)(remain_sec % 60); if (h < 100) { - snprintf(szTime, 100, "%.2d:%.2d:%.2d", h, m, s); + snprintf(time, 100, "%.2d:%.2d:%.2d", h, m, s); } else { - snprintf(szTime, 100, "99:99:99"); + snprintf(time, 100, "99:99:99"); } } - if (bCalcColWidth) + if (calcColWidth) { - int iColWidthFiles = strlen(szFiles); - m_iColWidthFiles = iColWidthFiles > m_iColWidthFiles ? iColWidthFiles : m_iColWidthFiles; + int colWidthFiles = strlen(files); + m_colWidthFiles = colWidthFiles > m_colWidthFiles ? colWidthFiles : m_colWidthFiles; - int iColWidthTotal = strlen(szTotal); - m_iColWidthTotal = iColWidthTotal > m_iColWidthTotal ? iColWidthTotal : m_iColWidthTotal; + int colWidthTotal = strlen(total); + m_colWidthTotal = colWidthTotal > m_colWidthTotal ? colWidthTotal : m_colWidthTotal; - int iColWidthLeft = strlen(szRemaining); - m_iColWidthLeft = iColWidthLeft > m_iColWidthLeft ? iColWidthLeft : m_iColWidthLeft; + int colWidthLeft = strlen(remaining); + m_colWidthLeft = colWidthLeft > m_colWidthLeft ? colWidthLeft : m_colWidthLeft; } else { - snprintf(szBuffer, MAX_SCREEN_WIDTH, "%-*s %*s %*s %*s %8s", iNameLen, szNameWithIds, m_iColWidthFiles, szFiles, m_iColWidthTotal, szTotal, m_iColWidthLeft, szRemaining, szTime); + snprintf(buffer, MAX_SCREEN_WIDTH, "%-*s %*s %*s %*s %8s", nameLen, nameWithIds, m_colWidthFiles, files, m_colWidthTotal, total, m_colWidthLeft, remaining, time); } } else { - snprintf(szBuffer, MAX_SCREEN_WIDTH, "%c%i%c%s %s", chBrace1, pNZBInfo->GetID(), - chBrace2, szDownloading, pNZBInfo->GetName()); + snprintf(buffer, MAX_SCREEN_WIDTH, "%c%i%c%s %s", chBrace1, nzbInfo->GetID(), + chBrace2, downloading, nzbInfo->GetName()); } - szBuffer[MAX_SCREEN_WIDTH - 1] = '\0'; + buffer[MAX_SCREEN_WIDTH - 1] = '\0'; - if (!bCalcColWidth) + if (!calcColWidth) { - PlotLine(szBuffer, iRow, 0, color); + PlotLine(buffer, row, 0, color); } } -bool NCursesFrontend::EditQueue(DownloadQueue::EEditAction eAction, int iOffset) +bool NCursesFrontend::EditQueue(DownloadQueue::EEditAction action, int offset) { int ID = 0; - if (m_bGroupFiles) + if (m_groupFiles) { - DownloadQueue* pDownloadQueue = LockQueue(); - if (m_iSelectedQueueEntry >= 0 && m_iSelectedQueueEntry < (int)pDownloadQueue->GetQueue()->size()) + DownloadQueue* downloadQueue = LockQueue(); + if (m_selectedQueueEntry >= 0 && m_selectedQueueEntry < (int)downloadQueue->GetQueue()->size()) { - NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->at(m_iSelectedQueueEntry); - ID = pNZBInfo->GetID(); - if (eAction == DownloadQueue::eaFilePause) + NZBInfo* nzbInfo = downloadQueue->GetQueue()->at(m_selectedQueueEntry); + ID = nzbInfo->GetID(); + if (action == DownloadQueue::eaFilePause) { - if (pNZBInfo->GetRemainingSize() == pNZBInfo->GetPausedSize()) + if (nzbInfo->GetRemainingSize() == nzbInfo->GetPausedSize()) { - eAction = DownloadQueue::eaFileResume; + action = DownloadQueue::eaFileResume; } - else if (pNZBInfo->GetPausedSize() == 0 && (pNZBInfo->GetRemainingParCount() > 0) && - !(m_bLastPausePars && m_iLastEditEntry == m_iSelectedQueueEntry)) + else if (nzbInfo->GetPausedSize() == 0 && (nzbInfo->GetRemainingParCount() > 0) && + !(m_lastPausePars && m_lastEditEntry == m_selectedQueueEntry)) { - eAction = DownloadQueue::eaFilePauseExtraPars; - m_bLastPausePars = true; + action = DownloadQueue::eaFilePauseExtraPars; + m_lastPausePars = true; } else { - eAction = DownloadQueue::eaFilePause; - m_bLastPausePars = false; + action = DownloadQueue::eaFilePause; + m_lastPausePars = false; } } } @@ -1151,25 +1151,25 @@ bool NCursesFrontend::EditQueue(DownloadQueue::EEditAction eAction, int iOffset) DownloadQueue::eaGroupDelete, DownloadQueue::eaGroupPauseAllPars, DownloadQueue::eaGroupPauseExtraPars }; - eAction = FileToGroupMap[eAction]; + action = FileToGroupMap[action]; } else { - DownloadQueue* pDownloadQueue = LockQueue(); + DownloadQueue* downloadQueue = LockQueue(); - int iFileNum = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + int fileNum = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++, iFileNum++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++, fileNum++) { - if (m_iSelectedQueueEntry == iFileNum) + if (m_selectedQueueEntry == fileNum) { - FileInfo* pFileInfo = *it2; - ID = pFileInfo->GetID(); - if (eAction == DownloadQueue::eaFilePause) + FileInfo* fileInfo = *it2; + ID = fileInfo->GetID(); + if (action == DownloadQueue::eaFilePause) { - eAction = !pFileInfo->GetPaused() ? DownloadQueue::eaFilePause : DownloadQueue::eaFileResume; + action = !fileInfo->GetPaused() ? DownloadQueue::eaFilePause : DownloadQueue::eaFileResume; } } } @@ -1178,13 +1178,13 @@ bool NCursesFrontend::EditQueue(DownloadQueue::EEditAction eAction, int iOffset) UnlockQueue(); } - m_iLastEditEntry = m_iSelectedQueueEntry; + m_lastEditEntry = m_selectedQueueEntry; NeedUpdateData(); if (ID != 0) { - return ServerEditQueue(eAction, iOffset, ID); + return ServerEditQueue(action, offset, ID); } else { @@ -1192,43 +1192,43 @@ bool NCursesFrontend::EditQueue(DownloadQueue::EEditAction eAction, int iOffset) } } -void NCursesFrontend::SetCurrentQueueEntry(int iEntry) +void NCursesFrontend::SetCurrentQueueEntry(int entry) { - int iQueueSize = CalcQueueSize(); + int queueSize = CalcQueueSize(); - if (iEntry < 0) + if (entry < 0) { - iEntry = 0; + entry = 0; } - else if (iEntry > iQueueSize - 1) + else if (entry > queueSize - 1) { - iEntry = iQueueSize - 1; + entry = queueSize - 1; } - if (iEntry > m_iQueueScrollOffset + m_iQueueWinClientHeight || - iEntry < m_iQueueScrollOffset - m_iQueueWinClientHeight) + if (entry > m_queueScrollOffset + m_queueWinClientHeight || + entry < m_queueScrollOffset - m_queueWinClientHeight) { - m_iQueueScrollOffset = iEntry - m_iQueueWinClientHeight / 2; + m_queueScrollOffset = entry - m_queueWinClientHeight / 2; } - else if (iEntry < m_iQueueScrollOffset) + else if (entry < m_queueScrollOffset) { - m_iQueueScrollOffset -= m_iQueueWinClientHeight; + m_queueScrollOffset -= m_queueWinClientHeight; } - else if (iEntry >= m_iQueueScrollOffset + m_iQueueWinClientHeight) + else if (entry >= m_queueScrollOffset + m_queueWinClientHeight) { - m_iQueueScrollOffset += m_iQueueWinClientHeight; + m_queueScrollOffset += m_queueWinClientHeight; } - if (m_iQueueScrollOffset > iQueueSize - m_iQueueWinClientHeight) + if (m_queueScrollOffset > queueSize - m_queueWinClientHeight) { - m_iQueueScrollOffset = iQueueSize - m_iQueueWinClientHeight; + m_queueScrollOffset = queueSize - m_queueWinClientHeight; } - if (m_iQueueScrollOffset < 0) + if (m_queueScrollOffset < 0) { - m_iQueueScrollOffset = 0; + m_queueScrollOffset = 0; } - m_iSelectedQueueEntry = iEntry; + m_selectedQueueEntry = entry; } @@ -1238,15 +1238,15 @@ void NCursesFrontend::SetCurrentQueueEntry(int iEntry) */ void NCursesFrontend::UpdateInput(int initialKey) { - int iKey = initialKey; - while (iKey != READKEY_EMPTY) + int key = initialKey; + while (key != READKEY_EMPTY) { - int iQueueSize = CalcQueueSize(); + int queueSize = CalcQueueSize(); // Normal or edit queue mode - if (m_eInputMode == eNormal || m_eInputMode == eEditQueue) + if (m_inputMode == normal || m_inputMode == editQueue) { - switch (iKey) + switch (key) { case 'q': // Key 'q' for quit @@ -1254,120 +1254,120 @@ void NCursesFrontend::UpdateInput(int initialKey) break; case 'z': // show/hide NZBFilename - m_bShowNZBname = !m_bShowNZBname; + m_showNzbname = !m_showNzbname; break; case 'w': // swicth window sizes - if (m_QueueWindowPercentage == 50) + if (m_queueWindowPercentage == 50) { - m_QueueWindowPercentage = 100; + m_queueWindowPercentage = 100; } - else if (m_QueueWindowPercentage == 100 && m_eInputMode != eEditQueue) + else if (m_queueWindowPercentage == 100 && m_inputMode != editQueue) { - m_QueueWindowPercentage = 0; + m_queueWindowPercentage = 0; } else { - m_QueueWindowPercentage = 50; + m_queueWindowPercentage = 50; } CalcWindowSizes(); - SetCurrentQueueEntry(m_iSelectedQueueEntry); + SetCurrentQueueEntry(m_selectedQueueEntry); break; case 'g': // group/ungroup files - m_bGroupFiles = !m_bGroupFiles; - SetCurrentQueueEntry(m_iSelectedQueueEntry); + m_groupFiles = !m_groupFiles; + SetCurrentQueueEntry(m_selectedQueueEntry); NeedUpdateData(); break; } } // Normal mode - if (m_eInputMode == eNormal) + if (m_inputMode == normal) { - switch (iKey) + switch (key) { case 'p': // Key 'p' for pause if (!IsRemoteMode()) { - info(m_bPauseDownload ? "Unpausing download" : "Pausing download"); + info(m_pauseDownload ? "Unpausing download" : "Pausing download"); } - ServerPauseUnpause(!m_bPauseDownload); + ServerPauseUnpause(!m_pauseDownload); break; case 'e': case 10: // return case 13: // enter - if (iQueueSize > 0) + if (queueSize > 0) { - m_eInputMode = eEditQueue; - if (m_QueueWindowPercentage == 0) + m_inputMode = editQueue; + if (m_queueWindowPercentage == 0) { - m_QueueWindowPercentage = 50; + m_queueWindowPercentage = 50; } return; } break; case 'r': // Download rate - m_eInputMode = eDownloadRate; - m_iInputNumberIndex = 0; - m_iInputValue = 0; + m_inputMode = downloadRate; + m_inputNumberIndex = 0; + m_inputValue = 0; return; case 't': // show/hide Timestamps - m_bShowTimestamp = !m_bShowTimestamp; + m_showTimestamp = !m_showTimestamp; break; } } // Edit Queue mode - if (m_eInputMode == eEditQueue) + if (m_inputMode == editQueue) { - switch (iKey) + switch (key) { case 'e': case 10: // return case 13: // enter - m_eInputMode = eNormal; + m_inputMode = normal; return; case KEY_DOWN: - if (m_iSelectedQueueEntry < iQueueSize - 1) + if (m_selectedQueueEntry < queueSize - 1) { - SetCurrentQueueEntry(m_iSelectedQueueEntry + 1); + SetCurrentQueueEntry(m_selectedQueueEntry + 1); } break; case KEY_UP: - if (m_iSelectedQueueEntry > 0) + if (m_selectedQueueEntry > 0) { - SetCurrentQueueEntry(m_iSelectedQueueEntry - 1); + SetCurrentQueueEntry(m_selectedQueueEntry - 1); } break; case KEY_PPAGE: - if (m_iSelectedQueueEntry > 0) + if (m_selectedQueueEntry > 0) { - if (m_iSelectedQueueEntry == m_iQueueScrollOffset) + if (m_selectedQueueEntry == m_queueScrollOffset) { - m_iQueueScrollOffset -= m_iQueueWinClientHeight; - SetCurrentQueueEntry(m_iSelectedQueueEntry - m_iQueueWinClientHeight); + m_queueScrollOffset -= m_queueWinClientHeight; + SetCurrentQueueEntry(m_selectedQueueEntry - m_queueWinClientHeight); } else { - SetCurrentQueueEntry(m_iQueueScrollOffset); + SetCurrentQueueEntry(m_queueScrollOffset); } } break; case KEY_NPAGE: - if (m_iSelectedQueueEntry < iQueueSize - 1) + if (m_selectedQueueEntry < queueSize - 1) { - if (m_iSelectedQueueEntry == m_iQueueScrollOffset + m_iQueueWinClientHeight - 1) + if (m_selectedQueueEntry == m_queueScrollOffset + m_queueWinClientHeight - 1) { - m_iQueueScrollOffset += m_iQueueWinClientHeight; - SetCurrentQueueEntry(m_iSelectedQueueEntry + m_iQueueWinClientHeight); + m_queueScrollOffset += m_queueWinClientHeight; + SetCurrentQueueEntry(m_selectedQueueEntry + m_queueWinClientHeight); } else { - SetCurrentQueueEntry(m_iQueueScrollOffset + m_iQueueWinClientHeight - 1); + SetCurrentQueueEntry(m_queueScrollOffset + m_queueWinClientHeight - 1); } } break; @@ -1375,7 +1375,7 @@ void NCursesFrontend::UpdateInput(int initialKey) SetCurrentQueueEntry(0); break; case KEY_END: - SetCurrentQueueEntry(iQueueSize > 0 ? iQueueSize - 1 : 0); + SetCurrentQueueEntry(queueSize > 0 ? queueSize - 1 : 0); break; case 'p': // Key 'p' for pause @@ -1388,19 +1388,19 @@ void NCursesFrontend::UpdateInput(int initialKey) // Delete entry if (EditQueue(DownloadQueue::eaFileDelete, 0)) { - SetCurrentQueueEntry(m_iSelectedQueueEntry); + SetCurrentQueueEntry(m_selectedQueueEntry); } break; case 'u': if (EditQueue(DownloadQueue::eaFileMoveOffset, -1)) { - SetCurrentQueueEntry(m_iSelectedQueueEntry - 1); + SetCurrentQueueEntry(m_selectedQueueEntry - 1); } break; case 'n': if (EditQueue(DownloadQueue::eaFileMoveOffset, +1)) { - SetCurrentQueueEntry(m_iSelectedQueueEntry + 1); + SetCurrentQueueEntry(m_selectedQueueEntry + 1); } break; case 't': @@ -1412,45 +1412,45 @@ void NCursesFrontend::UpdateInput(int initialKey) case 'b': if (EditQueue(DownloadQueue::eaFileMoveBottom, 0)) { - SetCurrentQueueEntry(iQueueSize > 0 ? iQueueSize - 1 : 0); + SetCurrentQueueEntry(queueSize > 0 ? queueSize - 1 : 0); } break; } } // Edit download rate input mode - if (m_eInputMode == eDownloadRate) + if (m_inputMode == downloadRate) { // Numbers - if (m_iInputNumberIndex < 5 && iKey >= '0' && iKey <= '9') + if (m_inputNumberIndex < 5 && key >= '0' && key <= '9') { - m_iInputValue = (m_iInputValue * 10) + (iKey - '0'); - m_iInputNumberIndex++; + m_inputValue = (m_inputValue * 10) + (key - '0'); + m_inputNumberIndex++; } // Enter - else if (iKey == 10 || iKey == 13) + else if (key == 10 || key == 13) { - ServerSetDownloadRate(m_iInputValue * 1024); - m_eInputMode = eNormal; + ServerSetDownloadRate(m_inputValue * 1024); + m_inputMode = normal; return; } // Escape - else if (iKey == 27) + else if (key == 27) { - m_eInputMode = eNormal; + m_inputMode = normal; return; } // Backspace - else if (m_iInputNumberIndex > 0 && iKey == KEY_BACKSPACE) + else if (m_inputNumberIndex > 0 && key == KEY_BACKSPACE) { - int iRemain = m_iInputValue % 10; + int remain = m_inputValue % 10; - m_iInputValue = (m_iInputValue - iRemain) / 10; - m_iInputNumberIndex--; + m_inputValue = (m_inputValue - remain) / 10; + m_inputNumberIndex--; } } - iKey = ReadConsoleKey(); + key = ReadConsoleKey(); } } @@ -1459,8 +1459,8 @@ int NCursesFrontend::ReadConsoleKey() #ifdef WIN32 HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE); DWORD NumberOfEvents; - BOOL bOK = GetNumberOfConsoleInputEvents(hConsole, &NumberOfEvents); - if (bOK && NumberOfEvents > 0) + BOOL ok = GetNumberOfConsoleInputEvents(hConsole, &NumberOfEvents); + if (ok && NumberOfEvents > 0) { while (NumberOfEvents--) { diff --git a/daemon/frontend/NCursesFrontend.h b/daemon/frontend/NCursesFrontend.h index da293ba5..632b43ef 100644 --- a/daemon/frontend/NCursesFrontend.h +++ b/daemon/frontend/NCursesFrontend.h @@ -42,77 +42,77 @@ private: enum EInputMode { - eNormal, - eEditQueue, - eDownloadRate + normal, + editQueue, + downloadRate }; - bool m_bUseColor; - int m_iDataUpdatePos; - bool m_bUpdateNextTime; - int m_iScreenHeight; - int m_iScreenWidth; - int m_iQueueWinTop; - int m_iQueueWinHeight; - int m_iQueueWinClientHeight; - int m_iMessagesWinTop; - int m_iMessagesWinHeight; - int m_iMessagesWinClientHeight; - int m_iSelectedQueueEntry; - int m_iLastEditEntry; - bool m_bLastPausePars; - int m_iQueueScrollOffset; - char* m_szHint; - time_t m_tStartHint; - int m_iColWidthFiles; - int m_iColWidthTotal; - int m_iColWidthLeft; + bool m_useColor; + int m_dataUpdatePos; + bool m_updateNextTime; + int m_screenHeight; + int m_screenWidth; + int m_queueWinTop; + int m_queueWinHeight; + int m_queueWinClientHeight; + int m_messagesWinTop; + int m_messagesWinHeight; + int m_messagesWinClientHeight; + int m_selectedQueueEntry; + int m_lastEditEntry; + bool m_lastPausePars; + int m_queueScrollOffset; + char* m_hint; + time_t m_startHint; + int m_colWidthFiles; + int m_colWidthTotal; + int m_colWidthLeft; // Inputting numbers - int m_iInputNumberIndex; - int m_iInputValue; + int m_inputNumberIndex; + int m_inputValue; #ifdef WIN32 - CHAR_INFO* m_pScreenBuffer; - CHAR_INFO* m_pOldScreenBuffer; - int m_iScreenBufferSize; - std::vector m_ColorAttr; + CHAR_INFO* m_screenBuffer; + CHAR_INFO* m_oldScreenBuffer; + int m_screenBufferSize; + std::vector m_colorAttr; #else - void* m_pWindow; // WINDOW* + void* m_window; // WINDOW* #endif - EInputMode m_eInputMode; - bool m_bShowNZBname; - bool m_bShowTimestamp; - bool m_bGroupFiles; - int m_QueueWindowPercentage; + EInputMode m_inputMode; + bool m_showNzbname; + bool m_showTimestamp; + bool m_groupFiles; + int m_queueWindowPercentage; #ifdef WIN32 - void init_pair(int iColorNumber, WORD wForeColor, WORD wBackColor); + void init_pair(int colorNumber, WORD wForeColor, WORD wBackColor); #endif - void PlotLine(const char * szString, int iRow, int iPos, int iColorPair); - void PlotText(const char * szString, int iRow, int iPos, int iColorPair, bool bBlink); + void PlotLine(const char * string, int row, int pos, int colorPair); + void PlotText(const char * string, int row, int pos, int colorPair, bool blink); void PrintMessages(); void PrintQueue(); void PrintFileQueue(); - void PrintFilename(FileInfo* pFileInfo, int iRow, bool bSelected); + void PrintFilename(FileInfo* fileInfo, int row, bool selected); void PrintGroupQueue(); void ResetColWidths(); - void PrintGroupname(NZBInfo* pNZBInfo, int iRow, bool bSelected, bool bCalcColWidth); - void PrintTopHeader(char* szHeader, int iLineNr, bool bUpTime); - int PrintMessage(Message* Msg, int iRow, int iMaxLines); + void PrintGroupname(NZBInfo* nzbInfo, int row, bool selected, bool calcColWidth); + void PrintTopHeader(char* header, int lineNr, bool upTime); + int PrintMessage(Message* Msg, int row, int maxLines); void PrintKeyInputBar(); void PrintStatus(); void UpdateInput(int initialKey); - void Update(int iKey); - void SetCurrentQueueEntry(int iEntry); + void Update(int key); + void SetCurrentQueueEntry(int entry); void CalcWindowSizes(); void RefreshScreen(); int ReadConsoleKey(); int CalcQueueSize(); void NeedUpdateData(); - bool EditQueue(DownloadQueue::EEditAction eAction, int iOffset); - void SetHint(const char* szHint); + bool EditQueue(DownloadQueue::EEditAction action, int offset); + void SetHint(const char* hint); protected: virtual void Run(); diff --git a/daemon/main/CommandLineParser.cpp b/daemon/main/CommandLineParser.cpp index 4249c124..fc0dea81 100644 --- a/daemon/main/CommandLineParser.cpp +++ b/daemon/main/CommandLineParser.cpp @@ -89,51 +89,51 @@ static char short_options[] = "c:hno:psvAB:DCE:G:K:LPR:STUQOVW:"; CommandLineParser::CommandLineParser(int argc, const char* argv[]) { - m_bNoConfig = false; - m_szConfigFilename = NULL; - m_bErrors = false; - m_bPrintVersion = false; - m_bPrintUsage = false; + m_noConfig = false; + m_configFilename = NULL; + m_errors = false; + m_printVersion = false; + m_printUsage = false; - m_iEditQueueAction = 0; - m_pEditQueueIDList = NULL; - m_iEditQueueIDCount = 0; - m_iEditQueueOffset = 0; - m_szEditQueueText = NULL; - m_szArgFilename = NULL; - m_szLastArg = NULL; - m_szAddCategory = NULL; - m_iAddPriority = 0; - m_szAddNZBFilename = NULL; - m_bAddPaused = false; - m_bServerMode = false; - m_bDaemonMode = false; - m_bRemoteClientMode = false; - m_bPrintOptions = false; - m_bAddTop = false; - m_szAddDupeKey = NULL; - m_iAddDupeScore = 0; - m_iAddDupeMode = 0; - m_iLogLines = 0; - m_iWriteLogKind = 0; - m_bTestBacktrace = false; - m_bWebGet = false; - m_szWebGetFilename = NULL; - m_bSigVerify = false; - m_szPubKeyFilename = NULL; - m_szSigFilename = NULL; - m_EMatchMode = mmID; - m_bPauseDownload = false; + m_editQueueAction = 0; + m_editQueueIdList = NULL; + m_editQueueIdCount = 0; + m_editQueueOffset = 0; + m_editQueueText = NULL; + m_argFilename = NULL; + m_lastArg = NULL; + m_addCategory = NULL; + m_addPriority = 0; + m_addNzbFilename = NULL; + m_addPaused = false; + m_serverMode = false; + m_daemonMode = false; + m_remoteClientMode = false; + m_printOptions = false; + m_addTop = false; + m_addDupeKey = NULL; + m_addDupeScore = 0; + m_addDupeMode = 0; + m_logLines = 0; + m_writeLogKind = 0; + m_testBacktrace = false; + m_webGet = false; + m_webGetFilename = NULL; + m_sigVerify = false; + m_pubKeyFilename = NULL; + m_sigFilename = NULL; + m_eMatchMode = mmID; + m_pauseDownload = false; InitCommandLine(argc, argv); if (argc == 1) { - m_bPrintUsage = true; + m_printUsage = true; return; } - if (!m_bPrintOptions && !m_bPrintUsage && !m_bPrintVersion) + if (!m_printOptions && !m_printUsage && !m_printVersion) { InitFileArg(argc, argv); } @@ -141,34 +141,34 @@ CommandLineParser::CommandLineParser(int argc, const char* argv[]) CommandLineParser::~CommandLineParser() { - free(m_szConfigFilename); - free(m_szArgFilename); - free(m_szAddCategory); - free(m_szEditQueueText); - free(m_szLastArg); - free(m_pEditQueueIDList); - free(m_szAddNZBFilename); - free(m_szAddDupeKey); - free(m_szWebGetFilename); - free(m_szPubKeyFilename); - free(m_szSigFilename); + free(m_configFilename); + free(m_argFilename); + free(m_addCategory); + free(m_editQueueText); + free(m_lastArg); + free(m_editQueueIdList); + free(m_addNzbFilename); + free(m_addDupeKey); + free(m_webGetFilename); + free(m_pubKeyFilename); + free(m_sigFilename); - for (NameList::iterator it = m_EditQueueNameList.begin(); it != m_EditQueueNameList.end(); it++) + for (NameList::iterator it = m_editQueueNameList.begin(); it != m_editQueueNameList.end(); it++) { free(*it); } - m_EditQueueNameList.clear(); + m_editQueueNameList.clear(); - for (NameList::iterator it = m_OptionList.begin(); it != m_OptionList.end(); it++) + for (NameList::iterator it = m_optionList.begin(); it != m_optionList.end(); it++) { free(*it); } - m_OptionList.clear(); + m_optionList.clear(); } void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) { - m_eClientOperation = opClientNoOperation; // default + m_clientOperation = opClientNoOperation; // default char** argv = (char**)malloc(sizeof(char*) * argc); for (int i = 0; i < argc; i++) @@ -195,33 +195,33 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) switch (c) { case 'c': - m_szConfigFilename = strdup(optarg); + m_configFilename = strdup(optarg); break; case 'n': - m_szConfigFilename = NULL; - m_bNoConfig = true; + m_configFilename = NULL; + m_noConfig = true; break; case 'h': - m_bPrintUsage = true; + m_printUsage = true; return; case 'v': - m_bPrintVersion = true; + m_printVersion = true; return; case 'p': - m_bPrintOptions = true; + m_printOptions = true; break; case 'o': - m_OptionList.push_back(strdup(optarg)); + m_optionList.push_back(strdup(optarg)); break; case 's': - m_bServerMode = true; + m_serverMode = true; break; case 'D': - m_bServerMode = true; - m_bDaemonMode = true; + m_serverMode = true; + m_daemonMode = true; break; case 'A': - m_eClientOperation = opClientRequestDownload; + m_clientOperation = opClientRequestDownload; while (true) { @@ -233,11 +233,11 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } else if (optarg && !strcasecmp(optarg, "T")) { - m_bAddTop = true; + m_addTop = true; } else if (optarg && !strcasecmp(optarg, "P")) { - m_bAddPaused = true; + m_addPaused = true; } else if (optarg && !strcasecmp(optarg, "I")) { @@ -247,7 +247,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'A'"); return; } - m_iAddPriority = atoi(argv[optind-1]); + m_addPriority = atoi(argv[optind-1]); } else if (optarg && !strcasecmp(optarg, "C")) { @@ -257,8 +257,8 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'A'"); return; } - free(m_szAddCategory); - m_szAddCategory = strdup(argv[optind-1]); + free(m_addCategory); + m_addCategory = strdup(argv[optind-1]); } else if (optarg && !strcasecmp(optarg, "N")) { @@ -268,8 +268,8 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'A'"); return; } - free(m_szAddNZBFilename); - m_szAddNZBFilename = strdup(argv[optind-1]); + free(m_addNzbFilename); + m_addNzbFilename = strdup(argv[optind-1]); } else if (optarg && !strcasecmp(optarg, "DK")) { @@ -279,8 +279,8 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'A'"); return; } - free(m_szAddDupeKey); - m_szAddDupeKey = strdup(argv[optind-1]); + free(m_addDupeKey); + m_addDupeKey = strdup(argv[optind-1]); } else if (optarg && !strcasecmp(optarg, "DS")) { @@ -290,7 +290,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'A'"); return; } - m_iAddDupeScore = atoi(argv[optind-1]); + m_addDupeScore = atoi(argv[optind-1]); } else if (optarg && !strcasecmp(optarg, "DM")) { @@ -301,18 +301,18 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) return; } - const char* szDupeMode = argv[optind-1]; - if (!strcasecmp(szDupeMode, "score")) + const char* dupeMode = argv[optind-1]; + if (!strcasecmp(dupeMode, "score")) { - m_iAddDupeMode = dmScore; + m_addDupeMode = dmScore; } - else if (!strcasecmp(szDupeMode, "all")) + else if (!strcasecmp(dupeMode, "all")) { - m_iAddDupeMode = dmAll; + m_addDupeMode = dmAll; } - else if (!strcasecmp(szDupeMode, "force")) + else if (!strcasecmp(dupeMode, "force")) { - m_iAddDupeMode = dmForce; + m_addDupeMode = dmForce; } else { @@ -332,32 +332,32 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) optarg = optind > argc ? NULL : argv[optind-1]; if (!optarg || !strncmp(optarg, "-", 1)) { - m_eClientOperation = opClientRequestListFiles; + m_clientOperation = opClientRequestListFiles; optind--; } else if (!strcasecmp(optarg, "F") || !strcasecmp(optarg, "FR")) { - m_eClientOperation = opClientRequestListFiles; + m_clientOperation = opClientRequestListFiles; } else if (!strcasecmp(optarg, "G") || !strcasecmp(optarg, "GR")) { - m_eClientOperation = opClientRequestListGroups; + m_clientOperation = opClientRequestListGroups; } else if (!strcasecmp(optarg, "O")) { - m_eClientOperation = opClientRequestPostQueue; + m_clientOperation = opClientRequestPostQueue; } else if (!strcasecmp(optarg, "S")) { - m_eClientOperation = opClientRequestListStatus; + m_clientOperation = opClientRequestListStatus; } else if (!strcasecmp(optarg, "H")) { - m_eClientOperation = opClientRequestHistory; + m_clientOperation = opClientRequestHistory; } else if (!strcasecmp(optarg, "HA")) { - m_eClientOperation = opClientRequestHistoryAll; + m_clientOperation = opClientRequestHistoryAll; } else { @@ -367,7 +367,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) if (optarg && (!strcasecmp(optarg, "FR") || !strcasecmp(optarg, "GR"))) { - m_EMatchMode = mmRegEx; + m_eMatchMode = mmRegEx; optind++; if (optind > argc) @@ -375,7 +375,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'L'"); return; } - m_szEditQueueText = strdup(argv[optind-1]); + m_editQueueText = strdup(argv[optind-1]); } break; case 'P': @@ -384,20 +384,20 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) optarg = optind > argc ? NULL : argv[optind-1]; if (!optarg || !strncmp(optarg, "-", 1)) { - m_eClientOperation = c == 'P' ? opClientRequestDownloadPause : opClientRequestDownloadUnpause; + m_clientOperation = c == 'P' ? opClientRequestDownloadPause : opClientRequestDownloadUnpause; optind--; } else if (!strcasecmp(optarg, "D")) { - m_eClientOperation = c == 'P' ? opClientRequestDownloadPause : opClientRequestDownloadUnpause; + m_clientOperation = c == 'P' ? opClientRequestDownloadPause : opClientRequestDownloadUnpause; } else if (!strcasecmp(optarg, "O")) { - m_eClientOperation = c == 'P' ? opClientRequestPostPause : opClientRequestPostUnpause; + m_clientOperation = c == 'P' ? opClientRequestPostPause : opClientRequestPostUnpause; } else if (!strcasecmp(optarg, "S")) { - m_eClientOperation = c == 'P' ? opClientRequestScanPause : opClientRequestScanUnpause; + m_clientOperation = c == 'P' ? opClientRequestScanPause : opClientRequestScanUnpause; } else { @@ -406,21 +406,21 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } break; case 'R': - m_eClientOperation = opClientRequestSetRate; - m_iSetRate = (int)(atof(optarg)*1024); + m_clientOperation = opClientRequestSetRate; + m_setRate = (int)(atof(optarg)*1024); break; case 'B': if (!strcasecmp(optarg, "dump")) { - m_eClientOperation = opClientRequestDumpDebug; + m_clientOperation = opClientRequestDumpDebug; } else if (!strcasecmp(optarg, "trace")) { - m_bTestBacktrace = true; + m_testBacktrace = true; } else if (!strcasecmp(optarg, "webget")) { - m_bWebGet = true; + m_webGet = true; optind++; if (optind > argc) { @@ -428,11 +428,11 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) return; } optarg = argv[optind-1]; - m_szWebGetFilename = strdup(optarg); + m_webGetFilename = strdup(optarg); } else if (!strcasecmp(optarg, "verify")) { - m_bSigVerify = true; + m_sigVerify = true; optind++; if (optind > argc) { @@ -440,7 +440,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) return; } optarg = argv[optind-1]; - m_szPubKeyFilename = strdup(optarg); + m_pubKeyFilename = strdup(optarg); optind++; if (optind > argc) @@ -449,7 +449,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) return; } optarg = argv[optind-1]; - m_szSigFilename = strdup(optarg); + m_sigFilename = strdup(optarg); } else { @@ -458,40 +458,40 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } break; case 'G': - m_eClientOperation = opClientRequestLog; - m_iLogLines = atoi(optarg); - if (m_iLogLines == 0) + m_clientOperation = opClientRequestLog; + m_logLines = atoi(optarg); + if (m_logLines == 0) { ReportError("Could not parse value of option 'G'"); return; } break; case 'T': - m_bAddTop = true; + m_addTop = true; break; case 'C': - m_bRemoteClientMode = true; + m_remoteClientMode = true; break; case 'E': { - m_eClientOperation = opClientRequestEditQueue; - bool bGroup = !strcasecmp(optarg, "G") || !strcasecmp(optarg, "GN") || !strcasecmp(optarg, "GR"); - bool bFile = !strcasecmp(optarg, "F") || !strcasecmp(optarg, "FN") || !strcasecmp(optarg, "FR"); + m_clientOperation = opClientRequestEditQueue; + bool group = !strcasecmp(optarg, "G") || !strcasecmp(optarg, "GN") || !strcasecmp(optarg, "GR"); + bool file = !strcasecmp(optarg, "F") || !strcasecmp(optarg, "FN") || !strcasecmp(optarg, "FR"); if (!strcasecmp(optarg, "GN") || !strcasecmp(optarg, "FN")) { - m_EMatchMode = mmName; + m_eMatchMode = mmName; } else if (!strcasecmp(optarg, "GR") || !strcasecmp(optarg, "FR")) { - m_EMatchMode = mmRegEx; + m_eMatchMode = mmRegEx; } else { - m_EMatchMode = mmID; + m_eMatchMode = mmID; }; - bool bPost = !strcasecmp(optarg, "O"); - bool bHistory = !strcasecmp(optarg, "H"); - if (bGroup || bFile || bPost || bHistory) + bool post = !strcasecmp(optarg, "O"); + bool history = !strcasecmp(optarg, "H"); + if (group || file || post || history) { optind++; if (optind > argc) @@ -502,12 +502,12 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) optarg = argv[optind-1]; } - if (bPost) + if (post) { // edit-commands for post-processor-queue if (!strcasecmp(optarg, "D")) { - m_iEditQueueAction = DownloadQueue::eaPostDelete; + m_editQueueAction = DownloadQueue::eaPostDelete; } else { @@ -515,28 +515,28 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) return; } } - else if (bHistory) + else if (history) { // edit-commands for history if (!strcasecmp(optarg, "D")) { - m_iEditQueueAction = DownloadQueue::eaHistoryDelete; + m_editQueueAction = DownloadQueue::eaHistoryDelete; } else if (!strcasecmp(optarg, "R")) { - m_iEditQueueAction = DownloadQueue::eaHistoryReturn; + m_editQueueAction = DownloadQueue::eaHistoryReturn; } else if (!strcasecmp(optarg, "P")) { - m_iEditQueueAction = DownloadQueue::eaHistoryProcess; + m_editQueueAction = DownloadQueue::eaHistoryProcess; } else if (!strcasecmp(optarg, "A")) { - m_iEditQueueAction = DownloadQueue::eaHistoryRedownload; + m_editQueueAction = DownloadQueue::eaHistoryRedownload; } else if (!strcasecmp(optarg, "O")) { - m_iEditQueueAction = DownloadQueue::eaHistorySetParameter; + m_editQueueAction = DownloadQueue::eaHistorySetParameter; optind++; if (optind > argc) @@ -544,9 +544,9 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'E'"); return; } - m_szEditQueueText = strdup(argv[optind-1]); + m_editQueueText = strdup(argv[optind-1]); - if (!strchr(m_szEditQueueText, '=')) + if (!strchr(m_editQueueText, '=')) { ReportError("Could not parse value of option 'E'"); return; @@ -554,15 +554,15 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } else if (!strcasecmp(optarg, "B")) { - m_iEditQueueAction = DownloadQueue::eaHistoryMarkBad; + m_editQueueAction = DownloadQueue::eaHistoryMarkBad; } else if (!strcasecmp(optarg, "G")) { - m_iEditQueueAction = DownloadQueue::eaHistoryMarkGood; + m_editQueueAction = DownloadQueue::eaHistoryMarkGood; } else if (!strcasecmp(optarg, "S")) { - m_iEditQueueAction = DownloadQueue::eaHistoryMarkSuccess; + m_editQueueAction = DownloadQueue::eaHistoryMarkSuccess; } else { @@ -575,41 +575,41 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) // edit-commands for download-queue if (!strcasecmp(optarg, "T")) { - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupMoveTop : DownloadQueue::eaFileMoveTop; + m_editQueueAction = group ? DownloadQueue::eaGroupMoveTop : DownloadQueue::eaFileMoveTop; } else if (!strcasecmp(optarg, "B")) { - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupMoveBottom : DownloadQueue::eaFileMoveBottom; + m_editQueueAction = group ? DownloadQueue::eaGroupMoveBottom : DownloadQueue::eaFileMoveBottom; } else if (!strcasecmp(optarg, "P")) { - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupPause : DownloadQueue::eaFilePause; + m_editQueueAction = group ? DownloadQueue::eaGroupPause : DownloadQueue::eaFilePause; } else if (!strcasecmp(optarg, "A")) { - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupPauseAllPars : DownloadQueue::eaFilePauseAllPars; + m_editQueueAction = group ? DownloadQueue::eaGroupPauseAllPars : DownloadQueue::eaFilePauseAllPars; } else if (!strcasecmp(optarg, "R")) { - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupPauseExtraPars : DownloadQueue::eaFilePauseExtraPars; + m_editQueueAction = group ? DownloadQueue::eaGroupPauseExtraPars : DownloadQueue::eaFilePauseExtraPars; } else if (!strcasecmp(optarg, "U")) { - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupResume : DownloadQueue::eaFileResume; + m_editQueueAction = group ? DownloadQueue::eaGroupResume : DownloadQueue::eaFileResume; } else if (!strcasecmp(optarg, "D")) { - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupDelete : DownloadQueue::eaFileDelete; + m_editQueueAction = group ? DownloadQueue::eaGroupDelete : DownloadQueue::eaFileDelete; } else if (!strcasecmp(optarg, "C") || !strcasecmp(optarg, "K") || !strcasecmp(optarg, "CP")) { // switch "K" is provided for compatibility with v. 0.8.0 and can be removed in future versions - if (!bGroup) + if (!group) { ReportError("Category can be set only for groups"); return; } - m_iEditQueueAction = !strcasecmp(optarg, "CP") ? DownloadQueue::eaGroupApplyCategory : DownloadQueue::eaGroupSetCategory; + m_editQueueAction = !strcasecmp(optarg, "CP") ? DownloadQueue::eaGroupApplyCategory : DownloadQueue::eaGroupSetCategory; optind++; if (optind > argc) @@ -617,16 +617,16 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'E'"); return; } - m_szEditQueueText = strdup(argv[optind-1]); + m_editQueueText = strdup(argv[optind-1]); } else if (!strcasecmp(optarg, "N")) { - if (!bGroup) + if (!group) { ReportError("Only groups can be renamed"); return; } - m_iEditQueueAction = DownloadQueue::eaGroupSetName; + m_editQueueAction = DownloadQueue::eaGroupSetName; optind++; if (optind > argc) @@ -634,20 +634,20 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'E'"); return; } - m_szEditQueueText = strdup(argv[optind-1]); + m_editQueueText = strdup(argv[optind-1]); } else if (!strcasecmp(optarg, "M")) { - if (!bGroup) + if (!group) { ReportError("Only groups can be merged"); return; } - m_iEditQueueAction = DownloadQueue::eaGroupMerge; + m_editQueueAction = DownloadQueue::eaGroupMerge; } else if (!strcasecmp(optarg, "S")) { - m_iEditQueueAction = DownloadQueue::eaFileSplit; + m_editQueueAction = DownloadQueue::eaFileSplit; optind++; if (optind > argc) @@ -655,16 +655,16 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'E'"); return; } - m_szEditQueueText = strdup(argv[optind-1]); + m_editQueueText = strdup(argv[optind-1]); } else if (!strcasecmp(optarg, "O")) { - if (!bGroup) + if (!group) { ReportError("Post-process parameter can be set only for groups"); return; } - m_iEditQueueAction = DownloadQueue::eaGroupSetParameter; + m_editQueueAction = DownloadQueue::eaGroupSetParameter; optind++; if (optind > argc) @@ -672,9 +672,9 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'E'"); return; } - m_szEditQueueText = strdup(argv[optind-1]); + m_editQueueText = strdup(argv[optind-1]); - if (!strchr(m_szEditQueueText, '=')) + if (!strchr(m_editQueueText, '=')) { ReportError("Could not parse value of option 'E'"); return; @@ -682,12 +682,12 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } else if (!strcasecmp(optarg, "I")) { - if (!bGroup) + if (!group) { ReportError("Priority can be set only for groups"); return; } - m_iEditQueueAction = DownloadQueue::eaGroupSetPriority; + m_editQueueAction = DownloadQueue::eaGroupSetPriority; optind++; if (optind > argc) @@ -695,9 +695,9 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) ReportError("Could not parse value of option 'E'"); return; } - m_szEditQueueText = strdup(argv[optind-1]); + m_editQueueText = strdup(argv[optind-1]); - if (atoi(m_szEditQueueText) == 0 && strcmp("0", m_szEditQueueText)) + if (atoi(m_editQueueText) == 0 && strcmp("0", m_editQueueText)) { ReportError("Could not parse value of option 'E'"); return; @@ -705,42 +705,42 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } else { - m_iEditQueueOffset = atoi(optarg); - if (m_iEditQueueOffset == 0) + m_editQueueOffset = atoi(optarg); + if (m_editQueueOffset == 0) { ReportError("Could not parse value of option 'E'"); return; } - m_iEditQueueAction = bGroup ? DownloadQueue::eaGroupMoveOffset : DownloadQueue::eaFileMoveOffset; + m_editQueueAction = group ? DownloadQueue::eaGroupMoveOffset : DownloadQueue::eaFileMoveOffset; } } break; } case 'Q': - m_eClientOperation = opClientRequestShutdown; + m_clientOperation = opClientRequestShutdown; break; case 'O': - m_eClientOperation = opClientRequestReload; + m_clientOperation = opClientRequestReload; break; case 'V': - m_eClientOperation = opClientRequestVersion; + m_clientOperation = opClientRequestVersion; break; case 'W': - m_eClientOperation = opClientRequestWriteLog; + m_clientOperation = opClientRequestWriteLog; if (!strcasecmp(optarg, "I")) { - m_iWriteLogKind = (int)Message::mkInfo; + m_writeLogKind = (int)Message::mkInfo; } else if (!strcasecmp(optarg, "W")) { - m_iWriteLogKind = (int)Message::mkWarning; + m_writeLogKind = (int)Message::mkWarning; } else if (!strcasecmp(optarg, "E")) { - m_iWriteLogKind = (int)Message::mkError; + m_writeLogKind = (int)Message::mkError; } else if (!strcasecmp(optarg, "D")) { - m_iWriteLogKind = (int)Message::mkDetail; + m_writeLogKind = (int)Message::mkDetail; } else if (!strcasecmp(optarg, "G")) { - m_iWriteLogKind = (int)Message::mkDebug; + m_writeLogKind = (int)Message::mkDebug; } else { @@ -750,20 +750,20 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) break; case 'K': // switch "K" is provided for compatibility with v. 0.8.0 and can be removed in future versions - free(m_szAddCategory); - m_szAddCategory = strdup(optarg); + free(m_addCategory); + m_addCategory = strdup(optarg); break; case 'S': optind++; optarg = optind > argc ? NULL : argv[optind-1]; if (!optarg || !strncmp(optarg, "-", 1)) { - m_eClientOperation = opClientRequestScanAsync; + m_clientOperation = opClientRequestScanAsync; optind--; } else if (!strcasecmp(optarg, "W")) { - m_eClientOperation = opClientRequestScanSync; + m_clientOperation = opClientRequestScanSync; } else { @@ -772,7 +772,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } break; case '?': - m_bErrors = true; + m_errors = true; return; } } @@ -783,10 +783,10 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) } free(argv); - if (m_bServerMode && m_eClientOperation == opClientRequestDownloadPause) + if (m_serverMode && m_clientOperation == opClientRequestDownloadPause) { - m_bPauseDownload = true; - m_eClientOperation = opClientNoOperation; + m_pauseDownload = true; + m_clientOperation = opClientNoOperation; } } @@ -902,12 +902,12 @@ void CommandLineParser::InitFileArg(int argc, const char* argv[]) if (optind >= argc) { // no nzb-file passed - if (!m_bServerMode && !m_bRemoteClientMode && - (m_eClientOperation == opClientNoOperation || - m_eClientOperation == opClientRequestDownload || - m_eClientOperation == opClientRequestWriteLog)) + if (!m_serverMode && !m_remoteClientMode && + (m_clientOperation == opClientNoOperation || + m_clientOperation == opClientRequestDownload || + m_clientOperation == opClientRequestWriteLog)) { - if (m_eClientOperation == opClientRequestWriteLog) + if (m_clientOperation == opClientRequestWriteLog) { ReportError("Log-text not specified"); } @@ -917,9 +917,9 @@ void CommandLineParser::InitFileArg(int argc, const char* argv[]) } } } - else if (m_eClientOperation == opClientRequestEditQueue) + else if (m_clientOperation == opClientRequestEditQueue) { - if (m_EMatchMode == mmID) + if (m_eMatchMode == mmID) { ParseFileIDList(argc, argv, optind); } @@ -930,34 +930,34 @@ void CommandLineParser::InitFileArg(int argc, const char* argv[]) } else { - m_szLastArg = strdup(argv[optind]); + m_lastArg = strdup(argv[optind]); // Check if the file-name is a relative path or an absolute path // If the path starts with '/' its an absolute, else relative - const char* szFileName = argv[optind]; + const char* fileName = argv[optind]; #ifdef WIN32 - m_szArgFilename = strdup(szFileName); + m_argFilename = strdup(fileName); #else - if (szFileName[0] == '/' || !strncasecmp(szFileName, "http://", 6) || !strncasecmp(szFileName, "https://", 7)) + if (fileName[0] == '/' || !strncasecmp(fileName, "http://", 6) || !strncasecmp(fileName, "https://", 7)) { - m_szArgFilename = strdup(szFileName); + m_argFilename = strdup(fileName); } else { // TEST - char szFileNameWithPath[1024]; - getcwd(szFileNameWithPath, 1024); - strcat(szFileNameWithPath, "/"); - strcat(szFileNameWithPath, szFileName); - m_szArgFilename = strdup(szFileNameWithPath); + char fileNameWithPath[1024]; + getcwd(fileNameWithPath, 1024); + strcat(fileNameWithPath, "/"); + strcat(fileNameWithPath, fileName); + m_argFilename = strdup(fileNameWithPath); } #endif - if (m_bServerMode || m_bRemoteClientMode || - !(m_eClientOperation == opClientNoOperation || - m_eClientOperation == opClientRequestDownload || - m_eClientOperation == opClientRequestWriteLog)) + if (m_serverMode || m_remoteClientMode || + !(m_clientOperation == opClientNoOperation || + m_clientOperation == opClientRequestDownload || + m_clientOperation == opClientRequestWriteLog)) { ReportError("Too many arguments"); } @@ -971,13 +971,13 @@ void CommandLineParser::ParseFileIDList(int argc, const char* argv[], int optind while (optind < argc) { - char* szWritableFileIDList = strdup(argv[optind++]); + char* writableFileIdList = strdup(argv[optind++]); - char* optarg = strtok(szWritableFileIDList, ", "); + char* optarg = strtok(writableFileIdList, ", "); while (optarg) { - int iEditQueueIDFrom = 0; - int iEditQueueIDTo = 0; + int editQueueIdFrom = 0; + int editQueueIdTo = 0; const char* p = strchr(optarg, '-'); if (p) { @@ -985,9 +985,9 @@ void CommandLineParser::ParseFileIDList(int argc, const char* argv[], int optind int maxlen = (int)(p - optarg < 100 ? p - optarg : 100); strncpy(buf, optarg, maxlen); buf[maxlen] = '\0'; - iEditQueueIDFrom = atoi(buf); - iEditQueueIDTo = atoi(p + 1); - if (iEditQueueIDFrom <= 0 || iEditQueueIDTo <= 0) + editQueueIdFrom = atoi(buf); + editQueueIdTo = atoi(p + 1); + if (editQueueIdFrom <= 0 || editQueueIdTo <= 0) { ReportError("invalid list of file IDs"); return; @@ -995,55 +995,55 @@ void CommandLineParser::ParseFileIDList(int argc, const char* argv[], int optind } else { - iEditQueueIDFrom = atoi(optarg); - if (iEditQueueIDFrom <= 0) + editQueueIdFrom = atoi(optarg); + if (editQueueIdFrom <= 0) { ReportError("invalid list of file IDs"); return; } - iEditQueueIDTo = iEditQueueIDFrom; + editQueueIdTo = editQueueIdFrom; } - int iEditQueueIDCount = 0; - if (iEditQueueIDTo != 0) + int editQueueIdCount = 0; + if (editQueueIdTo != 0) { - if (iEditQueueIDFrom < iEditQueueIDTo) + if (editQueueIdFrom < editQueueIdTo) { - iEditQueueIDCount = iEditQueueIDTo - iEditQueueIDFrom + 1; + editQueueIdCount = editQueueIdTo - editQueueIdFrom + 1; } else { - iEditQueueIDCount = iEditQueueIDFrom - iEditQueueIDTo + 1; + editQueueIdCount = editQueueIdFrom - editQueueIdTo + 1; } } else { - iEditQueueIDCount = 1; + editQueueIdCount = 1; } - for (int i = 0; i < iEditQueueIDCount; i++) + for (int i = 0; i < editQueueIdCount; i++) { - if (iEditQueueIDFrom < iEditQueueIDTo || iEditQueueIDTo == 0) + if (editQueueIdFrom < editQueueIdTo || editQueueIdTo == 0) { - IDs.push_back(iEditQueueIDFrom + i); + IDs.push_back(editQueueIdFrom + i); } else { - IDs.push_back(iEditQueueIDFrom - i); + IDs.push_back(editQueueIdFrom - i); } } optarg = strtok(NULL, ", "); } - free(szWritableFileIDList); + free(writableFileIdList); } - m_iEditQueueIDCount = IDs.size(); - m_pEditQueueIDList = (int*)malloc(sizeof(int) * m_iEditQueueIDCount); - for (int i = 0; i < m_iEditQueueIDCount; i++) + m_editQueueIdCount = IDs.size(); + m_editQueueIdList = (int*)malloc(sizeof(int) * m_editQueueIdCount); + for (int i = 0; i < m_editQueueIdCount; i++) { - m_pEditQueueIDList[i] = IDs[i]; + m_editQueueIdList[i] = IDs[i]; } } @@ -1051,12 +1051,12 @@ void CommandLineParser::ParseFileNameList(int argc, const char* argv[], int opti { while (optind < argc) { - m_EditQueueNameList.push_back(strdup(argv[optind++])); + m_editQueueNameList.push_back(strdup(argv[optind++])); } } -void CommandLineParser::ReportError(const char* szErrMessage) +void CommandLineParser::ReportError(const char* errMessage) { - m_bErrors = true; - printf("%s\n", szErrMessage); + m_errors = true; + printf("%s\n", errMessage); } diff --git a/daemon/main/CommandLineParser.h b/daemon/main/CommandLineParser.h index a2d033d0..eddb455d 100644 --- a/daemon/main/CommandLineParser.h +++ b/daemon/main/CommandLineParser.h @@ -70,53 +70,53 @@ public: typedef std::vector NameList; private: - bool m_bNoConfig; - char* m_szConfigFilename; + bool m_noConfig; + char* m_configFilename; // Parsed command-line parameters - bool m_bErrors; - bool m_bPrintVersion; - bool m_bPrintUsage; - bool m_bServerMode; - bool m_bDaemonMode; - bool m_bRemoteClientMode; - EClientOperation m_eClientOperation; - NameList m_OptionList; - int m_iEditQueueAction; - int m_iEditQueueOffset; - int* m_pEditQueueIDList; - int m_iEditQueueIDCount; - NameList m_EditQueueNameList; - EMatchMode m_EMatchMode; - char* m_szEditQueueText; - char* m_szArgFilename; - char* m_szAddCategory; - int m_iAddPriority; - bool m_bAddPaused; - char* m_szAddNZBFilename; - char* m_szLastArg; - bool m_bPrintOptions; - bool m_bAddTop; - char* m_szAddDupeKey; - int m_iAddDupeScore; - int m_iAddDupeMode; - int m_iSetRate; - int m_iLogLines; - int m_iWriteLogKind; - bool m_bTestBacktrace; - bool m_bWebGet; - char* m_szWebGetFilename; - bool m_bSigVerify; - char* m_szPubKeyFilename; - char* m_szSigFilename; - bool m_bPauseDownload; + bool m_errors; + bool m_printVersion; + bool m_printUsage; + bool m_serverMode; + bool m_daemonMode; + bool m_remoteClientMode; + EClientOperation m_clientOperation; + NameList m_optionList; + int m_editQueueAction; + int m_editQueueOffset; + int* m_editQueueIdList; + int m_editQueueIdCount; + NameList m_editQueueNameList; + EMatchMode m_eMatchMode; + char* m_editQueueText; + char* m_argFilename; + char* m_addCategory; + int m_addPriority; + bool m_addPaused; + char* m_addNzbFilename; + char* m_lastArg; + bool m_printOptions; + bool m_addTop; + char* m_addDupeKey; + int m_addDupeScore; + int m_addDupeMode; + int m_setRate; + int m_logLines; + int m_writeLogKind; + bool m_testBacktrace; + bool m_webGet; + char* m_webGetFilename; + bool m_sigVerify; + char* m_pubKeyFilename; + char* m_sigFilename; + bool m_pauseDownload; void InitCommandLine(int argc, const char* argv[]); void InitFileArg(int argc, const char* argv[]); void ParseFileIDList(int argc, const char* argv[], int optind); void ParseFileNameList(int argc, const char* argv[], int optind); - bool ParseTime(const char* szTime, int* pHours, int* pMinutes); - void ReportError(const char* szErrMessage); + bool ParseTime(const char* time, int* hours, int* minutes); + void ReportError(const char* errMessage); public: CommandLineParser(int argc, const char* argv[]); @@ -124,44 +124,44 @@ public: void PrintUsage(const char* com); - bool GetErrors() { return m_bErrors; } - bool GetNoConfig() { return m_bNoConfig; } - const char* GetConfigFilename() { return m_szConfigFilename; } - bool GetServerMode() { return m_bServerMode; } - bool GetDaemonMode() { return m_bDaemonMode; } - bool GetRemoteClientMode() { return m_bRemoteClientMode; } - EClientOperation GetClientOperation() { return m_eClientOperation; } - NameList* GetOptionList() { return &m_OptionList; } - int GetEditQueueAction() { return m_iEditQueueAction; } - int GetEditQueueOffset() { return m_iEditQueueOffset; } - int* GetEditQueueIDList() { return m_pEditQueueIDList; } - int GetEditQueueIDCount() { return m_iEditQueueIDCount; } - NameList* GetEditQueueNameList() { return &m_EditQueueNameList; } - EMatchMode GetMatchMode() { return m_EMatchMode; } - const char* GetEditQueueText() { return m_szEditQueueText; } - const char* GetArgFilename() { return m_szArgFilename; } - const char* GetAddCategory() { return m_szAddCategory; } - bool GetAddPaused() { return m_bAddPaused; } - const char* GetLastArg() { return m_szLastArg; } - int GetAddPriority() { return m_iAddPriority; } - char* GetAddNZBFilename() { return m_szAddNZBFilename; } - bool GetAddTop() { return m_bAddTop; } - const char* GetAddDupeKey() { return m_szAddDupeKey; } - int GetAddDupeScore() { return m_iAddDupeScore; } - int GetAddDupeMode() { return m_iAddDupeMode; } - int GetSetRate() { return m_iSetRate; } - int GetLogLines() { return m_iLogLines; } - int GetWriteLogKind() { return m_iWriteLogKind; } - bool GetTestBacktrace() { return m_bTestBacktrace; } - bool GetWebGet() { return m_bWebGet; } - const char* GetWebGetFilename() { return m_szWebGetFilename; } - bool GetSigVerify() { return m_bSigVerify; } - const char* GetPubKeyFilename() { return m_szPubKeyFilename; } - const char* GetSigFilename() { return m_szSigFilename; } - bool GetPrintOptions() { return m_bPrintOptions; } - bool GetPrintVersion() { return m_bPrintVersion; } - bool GetPrintUsage() { return m_bPrintUsage; } - bool GetPauseDownload() const { return m_bPauseDownload; } + bool GetErrors() { return m_errors; } + bool GetNoConfig() { return m_noConfig; } + const char* GetConfigFilename() { return m_configFilename; } + bool GetServerMode() { return m_serverMode; } + bool GetDaemonMode() { return m_daemonMode; } + bool GetRemoteClientMode() { return m_remoteClientMode; } + EClientOperation GetClientOperation() { return m_clientOperation; } + NameList* GetOptionList() { return &m_optionList; } + int GetEditQueueAction() { return m_editQueueAction; } + int GetEditQueueOffset() { return m_editQueueOffset; } + int* GetEditQueueIDList() { return m_editQueueIdList; } + int GetEditQueueIDCount() { return m_editQueueIdCount; } + NameList* GetEditQueueNameList() { return &m_editQueueNameList; } + EMatchMode GetMatchMode() { return m_eMatchMode; } + const char* GetEditQueueText() { return m_editQueueText; } + const char* GetArgFilename() { return m_argFilename; } + const char* GetAddCategory() { return m_addCategory; } + bool GetAddPaused() { return m_addPaused; } + const char* GetLastArg() { return m_lastArg; } + int GetAddPriority() { return m_addPriority; } + char* GetAddNZBFilename() { return m_addNzbFilename; } + bool GetAddTop() { return m_addTop; } + const char* GetAddDupeKey() { return m_addDupeKey; } + int GetAddDupeScore() { return m_addDupeScore; } + int GetAddDupeMode() { return m_addDupeMode; } + int GetSetRate() { return m_setRate; } + int GetLogLines() { return m_logLines; } + int GetWriteLogKind() { return m_writeLogKind; } + bool GetTestBacktrace() { return m_testBacktrace; } + bool GetWebGet() { return m_webGet; } + const char* GetWebGetFilename() { return m_webGetFilename; } + bool GetSigVerify() { return m_sigVerify; } + const char* GetPubKeyFilename() { return m_pubKeyFilename; } + const char* GetSigFilename() { return m_sigFilename; } + bool GetPrintOptions() { return m_printOptions; } + bool GetPrintVersion() { return m_printVersion; } + bool GetPrintUsage() { return m_printUsage; } + bool GetPauseDownload() const { return m_pauseDownload; } }; extern CommandLineParser* g_pCommandLineParser; diff --git a/daemon/main/DiskService.cpp b/daemon/main/DiskService.cpp index 1d91b808..fca884f8 100644 --- a/daemon/main/DiskService.cpp +++ b/daemon/main/DiskService.cpp @@ -49,15 +49,15 @@ DiskService::DiskService() { - m_iInterval = 0; - m_bWaitingReported = false; - m_bWaitingRequiredDir = true; + m_interval = 0; + m_waitingReported = false; + m_waitingRequiredDir = true; } void DiskService::ServiceWork() { - m_iInterval++; - if (m_iInterval == 5) + m_interval++; + if (m_interval == 5) { if (!g_pOptions->GetPauseDownload() && g_pOptions->GetDiskSpace() > 0 && !g_pStatMeter->GetStandBy()) @@ -65,10 +65,10 @@ void DiskService::ServiceWork() // check free disk space every 1 second CheckDiskSpace(); } - m_iInterval = 0; + m_interval = 0; } - if (m_bWaitingRequiredDir) + if (m_waitingRequiredDir) { CheckRequiredDir(); } @@ -76,8 +76,8 @@ void DiskService::ServiceWork() void DiskService::CheckDiskSpace() { - long long lFreeSpace = Util::FreeDiskSize(g_pOptions->GetDestDir()); - if (lFreeSpace > -1 && lFreeSpace / 1024 / 1024 < g_pOptions->GetDiskSpace()) + long long freeSpace = Util::FreeDiskSize(g_pOptions->GetDestDir()); + if (freeSpace > -1 && freeSpace / 1024 / 1024 < g_pOptions->GetDiskSpace()) { warn("Low disk space on %s. Pausing download", g_pOptions->GetDestDir()); g_pOptions->SetPauseDownload(true); @@ -85,8 +85,8 @@ void DiskService::CheckDiskSpace() if (!Util::EmptyStr(g_pOptions->GetInterDir())) { - lFreeSpace = Util::FreeDiskSize(g_pOptions->GetInterDir()); - if (lFreeSpace > -1 && lFreeSpace / 1024 / 1024 < g_pOptions->GetDiskSpace()) + freeSpace = Util::FreeDiskSize(g_pOptions->GetInterDir()); + if (freeSpace > -1 && freeSpace / 1024 / 1024 < g_pOptions->GetDiskSpace()) { warn("Low disk space on %s. Pausing download", g_pOptions->GetInterDir()); g_pOptions->SetPauseDownload(true); @@ -98,34 +98,34 @@ void DiskService::CheckRequiredDir() { if (!Util::EmptyStr(g_pOptions->GetRequiredDir())) { - bool bAllExist = true; - bool bWasWaitingReported = m_bWaitingReported; + bool allExist = true; + bool wasWaitingReported = m_waitingReported; // split RequiredDir into tokens Tokenizer tok(g_pOptions->GetRequiredDir(), ",;"); - while (const char* szDir = tok.Next()) + while (const char* dir = tok.Next()) { - if (!Util::FileExists(szDir) && !Util::DirectoryExists(szDir)) + if (!Util::FileExists(dir) && !Util::DirectoryExists(dir)) { - if (!bWasWaitingReported) + if (!wasWaitingReported) { - info("Waiting for required directory %s", szDir); - m_bWaitingReported = true; + info("Waiting for required directory %s", dir); + m_waitingReported = true; } - bAllExist = false; + allExist = false; } } - if (!bAllExist) + if (!allExist) { return; } } - if (m_bWaitingReported) + if (m_waitingReported) { info("All required directories available"); } g_pOptions->SetTempPauseDownload(false); g_pOptions->SetTempPausePostprocess(false); - m_bWaitingRequiredDir = false; + m_waitingRequiredDir = false; } diff --git a/daemon/main/DiskService.h b/daemon/main/DiskService.h index 8a2ff33d..2f383036 100644 --- a/daemon/main/DiskService.h +++ b/daemon/main/DiskService.h @@ -31,9 +31,9 @@ class DiskService : public Service { private: - int m_iInterval; - bool m_bWaitingRequiredDir; - bool m_bWaitingReported; + int m_interval; + bool m_waitingRequiredDir; + bool m_waitingReported; void CheckDiskSpace(); void CheckRequiredDir(); diff --git a/daemon/main/Maintenance.cpp b/daemon/main/Maintenance.cpp index cced7f64..240873fe 100644 --- a/daemon/main/Maintenance.cpp +++ b/daemon/main/Maintenance.cpp @@ -62,19 +62,19 @@ extern char* (*g_szArguments)[]; class Signature { private: - const char* m_szInFilename; - const char* m_szSigFilename; - const char* m_szPubKeyFilename; - unsigned char m_InHash[SHA256_DIGEST_LENGTH]; - unsigned char m_Signature[256]; - RSA* m_pPubKey; + const char* m_inFilename; + const char* m_sigFilename; + const char* m_pubKeyFilename; + unsigned char m_inHash[SHA256_DIGEST_LENGTH]; + unsigned char m_signature[256]; + RSA* m_pubKey; bool ReadSignature(); bool ComputeInHash(); bool ReadPubKey(); public: - Signature(const char* szInFilename, const char* szSigFilename, const char* szPubKeyFilename); + Signature(const char* inFilename, const char* sigFilename, const char* pubKeyFilename); ~Signature(); bool Verify(); }; @@ -83,155 +83,155 @@ public: Maintenance::Maintenance() { - m_iIDMessageGen = 0; - m_UpdateScriptController = NULL; - m_szUpdateScript = NULL; + m_idMessageGen = 0; + m_updateScriptController = NULL; + m_updateScript = NULL; } Maintenance::~Maintenance() { - m_mutexController.Lock(); - if (m_UpdateScriptController) + m_controllerMutex.Lock(); + if (m_updateScriptController) { - m_UpdateScriptController->Detach(); - m_mutexController.Unlock(); - while (m_UpdateScriptController) + m_updateScriptController->Detach(); + m_controllerMutex.Unlock(); + while (m_updateScriptController) { usleep(20*1000); } } - m_Messages.Clear(); + m_messages.Clear(); - free(m_szUpdateScript); + free(m_updateScript); } void Maintenance::ResetUpdateController() { - m_mutexController.Lock(); - m_UpdateScriptController = NULL; - m_mutexController.Unlock(); + m_controllerMutex.Lock(); + m_updateScriptController = NULL; + m_controllerMutex.Unlock(); } MessageList* Maintenance::LockMessages() { - m_mutexLog.Lock(); - return &m_Messages; + m_logMutex.Lock(); + return &m_messages; } void Maintenance::UnlockMessages() { - m_mutexLog.Unlock(); + m_logMutex.Unlock(); } -void Maintenance::AddMessage(Message::EKind eKind, time_t tTime, const char * szText) +void Maintenance::AddMessage(Message::EKind kind, time_t time, const char * text) { - if (tTime == 0) + if (time == 0) { - tTime = time(NULL); + time = ::time(NULL); } - m_mutexLog.Lock(); - Message* pMessage = new Message(++m_iIDMessageGen, eKind, tTime, szText); - m_Messages.push_back(pMessage); - m_mutexLog.Unlock(); + m_logMutex.Lock(); + Message* message = new Message(++m_idMessageGen, kind, time, text); + m_messages.push_back(message); + m_logMutex.Unlock(); } -bool Maintenance::StartUpdate(EBranch eBranch) +bool Maintenance::StartUpdate(EBranch branch) { - m_mutexController.Lock(); - bool bAlreadyUpdating = m_UpdateScriptController != NULL; - m_mutexController.Unlock(); + m_controllerMutex.Lock(); + bool alreadyUpdating = m_updateScriptController != NULL; + m_controllerMutex.Unlock(); - if (bAlreadyUpdating) + if (alreadyUpdating) { error("Could not start update-script: update-script is already running"); return false; } - if (m_szUpdateScript) + if (m_updateScript) { - free(m_szUpdateScript); - m_szUpdateScript = NULL; + free(m_updateScript); + m_updateScript = NULL; } - if (!ReadPackageInfoStr("install-script", &m_szUpdateScript)) + if (!ReadPackageInfoStr("install-script", &m_updateScript)) { return false; } // make absolute path - if (m_szUpdateScript[0] != PATH_SEPARATOR + if (m_updateScript[0] != PATH_SEPARATOR #ifdef WIN32 - && !(strlen(m_szUpdateScript) > 2 && m_szUpdateScript[1] == ':') + && !(strlen(m_updateScript) > 2 && m_updateScript[1] == ':') #endif ) { - char szFilename[MAX_PATH + 100]; - snprintf(szFilename, sizeof(szFilename), "%s%c%s", g_pOptions->GetAppDir(), PATH_SEPARATOR, m_szUpdateScript); - free(m_szUpdateScript); - m_szUpdateScript = strdup(szFilename); + char filename[MAX_PATH + 100]; + snprintf(filename, sizeof(filename), "%s%c%s", g_pOptions->GetAppDir(), PATH_SEPARATOR, m_updateScript); + free(m_updateScript); + m_updateScript = strdup(filename); } - m_Messages.Clear(); + m_messages.Clear(); - m_UpdateScriptController = new UpdateScriptController(); - m_UpdateScriptController->SetScript(m_szUpdateScript); - m_UpdateScriptController->SetBranch(eBranch); - m_UpdateScriptController->SetAutoDestroy(true); + m_updateScriptController = new UpdateScriptController(); + m_updateScriptController->SetScript(m_updateScript); + m_updateScriptController->SetBranch(branch); + m_updateScriptController->SetAutoDestroy(true); - m_UpdateScriptController->Start(); + m_updateScriptController->Start(); return true; } -bool Maintenance::CheckUpdates(char** pUpdateInfo) +bool Maintenance::CheckUpdates(char** updateInfo) { - char* szUpdateInfoScript; - if (!ReadPackageInfoStr("update-info-script", &szUpdateInfoScript)) + char* updateInfoScript; + if (!ReadPackageInfoStr("update-info-script", &updateInfoScript)) { return false; } - *pUpdateInfo = NULL; - UpdateInfoScriptController::ExecuteScript(szUpdateInfoScript, pUpdateInfo); + *updateInfo = NULL; + UpdateInfoScriptController::ExecuteScript(updateInfoScript, updateInfo); - free(szUpdateInfoScript); + free(updateInfoScript); - return *pUpdateInfo; + return *updateInfo; } -bool Maintenance::ReadPackageInfoStr(const char* szKey, char** pValue) +bool Maintenance::ReadPackageInfoStr(const char* key, char** value) { - char szFileName[1024]; - snprintf(szFileName, 1024, "%s%cpackage-info.json", g_pOptions->GetWebDir(), PATH_SEPARATOR); - szFileName[1024-1] = '\0'; + char fileName[1024]; + snprintf(fileName, 1024, "%s%cpackage-info.json", g_pOptions->GetWebDir(), PATH_SEPARATOR); + fileName[1024-1] = '\0'; - char* szPackageInfo; - int iPackageInfoLen; - if (!Util::LoadFileIntoBuffer(szFileName, &szPackageInfo, &iPackageInfoLen)) + char* packageInfo; + int packageInfoLen; + if (!Util::LoadFileIntoBuffer(fileName, &packageInfo, &packageInfoLen)) { - error("Could not load file %s", szFileName); + error("Could not load file %s", fileName); return false; } - char szKeyStr[100]; - snprintf(szKeyStr, 100, "\"%s\"", szKey); - szKeyStr[100-1] = '\0'; + char keyStr[100]; + snprintf(keyStr, 100, "\"%s\"", key); + keyStr[100-1] = '\0'; - char* p = strstr(szPackageInfo, szKeyStr); + char* p = strstr(packageInfo, keyStr); if (!p) { - error("Could not parse file %s", szFileName); - free(szPackageInfo); + error("Could not parse file %s", fileName); + free(packageInfo); return false; } - p = strchr(p + strlen(szKeyStr), '"'); + p = strchr(p + strlen(keyStr), '"'); if (!p) { - error("Could not parse file %s", szFileName); - free(szPackageInfo); + error("Could not parse file %s", fileName); + free(packageInfo); return false; } @@ -239,34 +239,34 @@ bool Maintenance::ReadPackageInfoStr(const char* szKey, char** pValue) char* pend = strchr(p, '"'); if (!pend) { - error("Could not parse file %s", szFileName); - free(szPackageInfo); + error("Could not parse file %s", fileName); + free(packageInfo); return false; } - int iLen = pend - p; - if (iLen >= sizeof(szFileName)) + int len = pend - p; + if (len >= sizeof(fileName)) { - error("Could not parse file %s", szFileName); - free(szPackageInfo); + error("Could not parse file %s", fileName); + free(packageInfo); return false; } - *pValue = (char*)malloc(iLen+1); - strncpy(*pValue, p, iLen); - (*pValue)[iLen] = '\0'; + *value = (char*)malloc(len+1); + strncpy(*value, p, len); + (*value)[len] = '\0'; - WebUtil::JsonDecode(*pValue); + WebUtil::JsonDecode(*value); - free(szPackageInfo); + free(packageInfo); return true; } -bool Maintenance::VerifySignature(const char* szInFilename, const char* szSigFilename, const char* szPubKeyFilename) +bool Maintenance::VerifySignature(const char* inFilename, const char* sigFilename, const char* pubKeyFilename) { #ifdef HAVE_OPENSSL - Signature signature(szInFilename, szSigFilename, szPubKeyFilename); + Signature signature(inFilename, sigFilename, pubKeyFilename); return signature.Verify(); #else return false; @@ -278,145 +278,145 @@ void UpdateScriptController::Run() // the update-script should not be automatically terminated when the program quits UnregisterRunningScript(); - m_iPrefixLen = 0; + m_prefixLen = 0; PrintMessage(Message::mkInfo, "Executing update-script %s", GetScript()); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "update-script %s", Util::BaseFileName(GetScript())); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "update-script %s", Util::BaseFileName(GetScript())); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - const char* szBranchName[] = { "STABLE", "TESTING", "DEVEL" }; - SetEnvVar("NZBUP_BRANCH", szBranchName[m_eBranch]); + const char* branchName[] = { "STABLE", "TESTING", "DEVEL" }; + SetEnvVar("NZBUP_BRANCH", branchName[m_branch]); SetEnvVar("NZBUP_RUNMODE", g_pCommandLineParser->GetDaemonMode() ? "DAEMON" : "SERVER"); for (int i = 0; i < g_iArgumentCount; i++) { - char szEnvName[40]; - snprintf(szEnvName, 40, "NZBUP_CMDLINE%i", i); - szInfoName[40-1] = '\0'; - SetEnvVar(szEnvName, (*g_szArguments)[i]); + char envName[40]; + snprintf(envName, 40, "NZBUP_CMDLINE%i", i); + infoName[40-1] = '\0'; + SetEnvVar(envName, (*g_szArguments)[i]); } - char szProcessID[20]; + char processId[20]; #ifdef WIN32 int pid = (int)GetCurrentProcessId(); #else int pid = (int)getpid(); #endif - snprintf(szProcessID, 20, "%i", pid); - szProcessID[20-1] = '\0'; - SetEnvVar("NZBUP_PROCESSID", szProcessID); + snprintf(processId, 20, "%i", pid); + processId[20-1] = '\0'; + SetEnvVar("NZBUP_PROCESSID", processId); - char szLogPrefix[100]; - strncpy(szLogPrefix, Util::BaseFileName(GetScript()), 100); - szLogPrefix[100-1] = '\0'; - if (char* ext = strrchr(szLogPrefix, '.')) *ext = '\0'; // strip file extension - SetLogPrefix(szLogPrefix); - m_iPrefixLen = strlen(szLogPrefix) + 2; // 2 = strlen(": "); + char logPrefix[100]; + strncpy(logPrefix, Util::BaseFileName(GetScript()), 100); + logPrefix[100-1] = '\0'; + if (char* ext = strrchr(logPrefix, '.')) *ext = '\0'; // strip file extension + SetLogPrefix(logPrefix); + m_prefixLen = strlen(logPrefix) + 2; // 2 = strlen(": "); Execute(); g_pMaintenance->ResetUpdateController(); } -void UpdateScriptController::AddMessage(Message::EKind eKind, const char* szText) +void UpdateScriptController::AddMessage(Message::EKind kind, const char* text) { - szText = szText + m_iPrefixLen; + text = text + m_prefixLen; - if (!strncmp(szText, "[NZB] ", 6)) + if (!strncmp(text, "[NZB] ", 6)) { - debug("Command %s detected", szText + 6); - if (!strcmp(szText + 6, "QUIT")) + debug("Command %s detected", text + 6); + if (!strcmp(text + 6, "QUIT")) { Detach(); ExitProc(); } else { - error("Invalid command \"%s\" received", szText); + error("Invalid command \"%s\" received", text); } } else { - g_pMaintenance->AddMessage(eKind, time(NULL), szText); - ScriptController::AddMessage(eKind, szText); + g_pMaintenance->AddMessage(kind, time(NULL), text); + ScriptController::AddMessage(kind, text); } } -void UpdateInfoScriptController::ExecuteScript(const char* szScript, char** pUpdateInfo) +void UpdateInfoScriptController::ExecuteScript(const char* script, char** updateInfo) { - detail("Executing update-info-script %s", Util::BaseFileName(szScript)); + detail("Executing update-info-script %s", Util::BaseFileName(script)); - UpdateInfoScriptController* pScriptController = new UpdateInfoScriptController(); - pScriptController->SetScript(szScript); + UpdateInfoScriptController* scriptController = new UpdateInfoScriptController(); + scriptController->SetScript(script); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "update-info-script %s", Util::BaseFileName(szScript)); - szInfoName[1024-1] = '\0'; - pScriptController->SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "update-info-script %s", Util::BaseFileName(script)); + infoName[1024-1] = '\0'; + scriptController->SetInfoName(infoName); - char szLogPrefix[1024]; - strncpy(szLogPrefix, Util::BaseFileName(szScript), 1024); - szLogPrefix[1024-1] = '\0'; - if (char* ext = strrchr(szLogPrefix, '.')) *ext = '\0'; // strip file extension - pScriptController->SetLogPrefix(szLogPrefix); - pScriptController->m_iPrefixLen = strlen(szLogPrefix) + 2; // 2 = strlen(": "); + char logPrefix[1024]; + strncpy(logPrefix, Util::BaseFileName(script), 1024); + logPrefix[1024-1] = '\0'; + if (char* ext = strrchr(logPrefix, '.')) *ext = '\0'; // strip file extension + scriptController->SetLogPrefix(logPrefix); + scriptController->m_prefixLen = strlen(logPrefix) + 2; // 2 = strlen(": "); - pScriptController->Execute(); + scriptController->Execute(); - if (pScriptController->m_UpdateInfo.GetBuffer()) + if (scriptController->m_updateInfo.GetBuffer()) { - int iLen = strlen(pScriptController->m_UpdateInfo.GetBuffer()); - *pUpdateInfo = (char*)malloc(iLen + 1); - strncpy(*pUpdateInfo, pScriptController->m_UpdateInfo.GetBuffer(), iLen); - (*pUpdateInfo)[iLen] = '\0'; + int len = strlen(scriptController->m_updateInfo.GetBuffer()); + *updateInfo = (char*)malloc(len + 1); + strncpy(*updateInfo, scriptController->m_updateInfo.GetBuffer(), len); + (*updateInfo)[len] = '\0'; } - delete pScriptController; + delete scriptController; } -void UpdateInfoScriptController::AddMessage(Message::EKind eKind, const char* szText) +void UpdateInfoScriptController::AddMessage(Message::EKind kind, const char* text) { - szText = szText + m_iPrefixLen; + text = text + m_prefixLen; - if (!strncmp(szText, "[NZB] ", 6)) + if (!strncmp(text, "[NZB] ", 6)) { - debug("Command %s detected", szText + 6); - if (!strncmp(szText + 6, "[UPDATEINFO]", 12)) + debug("Command %s detected", text + 6); + if (!strncmp(text + 6, "[UPDATEINFO]", 12)) { - m_UpdateInfo.Append(szText + 6 + 12); + m_updateInfo.Append(text + 6 + 12); } else { - error("Invalid command \"%s\" received from %s", szText, GetInfoName()); + error("Invalid command \"%s\" received from %s", text, GetInfoName()); } } else { - ScriptController::AddMessage(eKind, szText); + ScriptController::AddMessage(kind, text); } } #ifdef HAVE_OPENSSL -Signature::Signature(const char *szInFilename, const char *szSigFilename, const char *szPubKeyFilename) +Signature::Signature(const char *inFilename, const char *sigFilename, const char *pubKeyFilename) { - m_szInFilename = szInFilename; - m_szSigFilename = szSigFilename; - m_szPubKeyFilename = szPubKeyFilename; - m_pPubKey = NULL; + m_inFilename = inFilename; + m_sigFilename = sigFilename; + m_pubKeyFilename = pubKeyFilename; + m_pubKey = NULL; } Signature::~Signature() { - RSA_free(m_pPubKey); + RSA_free(m_pubKey); } // Calculate SHA-256 for input file (m_szInFilename) bool Signature::ComputeInHash() { - FILE* infile = fopen(m_szInFilename, FOPEN_RB); + FILE* infile = fopen(m_inFilename, FOPEN_RB); if (!infile) { return false; @@ -429,7 +429,7 @@ bool Signature::ComputeInHash() { SHA256_Update(&sha256, buffer, bytesRead); } - SHA256_Final(m_InHash, &sha256); + SHA256_Final(m_inHash, &sha256); free(buffer); fclose(infile); return true; @@ -438,34 +438,34 @@ bool Signature::ComputeInHash() // Read signature from file (m_szSigFilename) into memory bool Signature::ReadSignature() { - char szSigTitle[256]; - snprintf(szSigTitle, sizeof(szSigTitle), "\"RSA-SHA256(%s)\" : \"", Util::BaseFileName(m_szInFilename)); - szSigTitle[256-1] = '\0'; + char sigTitle[256]; + snprintf(sigTitle, sizeof(sigTitle), "\"RSA-SHA256(%s)\" : \"", Util::BaseFileName(m_inFilename)); + sigTitle[256-1] = '\0'; - FILE* infile = fopen(m_szSigFilename, FOPEN_RB); + FILE* infile = fopen(m_sigFilename, FOPEN_RB); if (!infile) { return false; } - bool bOK = false; - int iTitLen = strlen(szSigTitle); + bool ok = false; + int titLen = strlen(sigTitle); char buf[1024]; - unsigned char* output = m_Signature; + unsigned char* output = m_signature; while (fgets(buf, sizeof(buf) - 1, infile)) { - if (!strncmp(buf, szSigTitle, iTitLen)) + if (!strncmp(buf, sigTitle, titLen)) { - char* szHexSig = buf + iTitLen; - int iSigLen = strlen(szHexSig); - if (iSigLen > 2) + char* hexSig = buf + titLen; + int sigLen = strlen(hexSig); + if (sigLen > 2) { - szHexSig[iSigLen - 2] = '\0'; // trim trailing ", + hexSig[sigLen - 2] = '\0'; // trim trailing ", } - for (; *szHexSig && *(szHexSig+1);) + for (; *hexSig && *(hexSig+1);) { - unsigned char c1 = *szHexSig++; - unsigned char c2 = *szHexSig++; + unsigned char c1 = *hexSig++; + unsigned char c2 = *hexSig++; c1 = '0' <= c1 && c1 <= '9' ? c1 - '0' : 'A' <= c1 && c1 <= 'F' ? c1 - 'A' + 10 : 'a' <= c1 && c1 <= 'f' ? c1 - 'a' + 10 : 0; c2 = '0' <= c2 && c2 <= '9' ? c2 - '0' : 'A' <= c2 && c2 <= 'F' ? c2 - 'A' + 10 : @@ -473,14 +473,14 @@ bool Signature::ReadSignature() unsigned char ch = (c1 << 4) + c2; *output++ = (char)ch; } - bOK = output == m_Signature + sizeof(m_Signature); + ok = output == m_signature + sizeof(m_signature); break; } } fclose(infile); - return bOK; + return ok; } // Read public key from file (m_szPubKeyFilename) into memory @@ -488,20 +488,20 @@ bool Signature::ReadPubKey() { char* keybuf; int keybuflen; - if (!Util::LoadFileIntoBuffer(m_szPubKeyFilename, &keybuf, &keybuflen)) + if (!Util::LoadFileIntoBuffer(m_pubKeyFilename, &keybuf, &keybuflen)) { return false; } BIO* mem = BIO_new_mem_buf(keybuf, keybuflen); - m_pPubKey = PEM_read_bio_RSA_PUBKEY(mem, NULL, NULL, NULL); + m_pubKey = PEM_read_bio_RSA_PUBKEY(mem, NULL, NULL, NULL); BIO_free(mem); free(keybuf); - return m_pPubKey != NULL; + return m_pubKey != NULL; } bool Signature::Verify() { return ComputeInHash() && ReadSignature() && ReadPubKey() && - RSA_verify(NID_sha256, m_InHash, sizeof(m_InHash), m_Signature, sizeof(m_Signature), m_pPubKey) == 1; + RSA_verify(NID_sha256, m_inHash, sizeof(m_inHash), m_signature, sizeof(m_signature), m_pubKey) == 1; } #endif /* HAVE_OPENSSL */ diff --git a/daemon/main/Maintenance.h b/daemon/main/Maintenance.h index da5ea816..4a2c8daa 100644 --- a/daemon/main/Maintenance.h +++ b/daemon/main/Maintenance.h @@ -35,14 +35,14 @@ class UpdateScriptController; class Maintenance { private: - MessageList m_Messages; - Mutex m_mutexLog; - Mutex m_mutexController; - int m_iIDMessageGen; - UpdateScriptController* m_UpdateScriptController; - char* m_szUpdateScript; + MessageList m_messages; + Mutex m_logMutex; + Mutex m_controllerMutex; + int m_idMessageGen; + UpdateScriptController* m_updateScriptController; + char* m_updateScript; - bool ReadPackageInfoStr(const char* szKey, char** pValue); + bool ReadPackageInfoStr(const char* key, char** value); public: enum EBranch @@ -54,13 +54,13 @@ public: Maintenance(); ~Maintenance(); - void AddMessage(Message::EKind eKind, time_t tTime, const char* szText); + void AddMessage(Message::EKind kind, time_t time, const char* text); MessageList* LockMessages(); void UnlockMessages(); - bool StartUpdate(EBranch eBranch); + bool StartUpdate(EBranch branch); void ResetUpdateController(); - bool CheckUpdates(char** pUpdateInfo); - static bool VerifySignature(const char* szInFilename, const char* szSigFilename, const char* szPubKeyFilename); + bool CheckUpdates(char** updateInfo); + static bool VerifySignature(const char* inFilename, const char* sigFilename, const char* pubKeyFilename); }; extern Maintenance* g_pMaintenance; @@ -68,28 +68,28 @@ extern Maintenance* g_pMaintenance; class UpdateScriptController : public Thread, public ScriptController { private: - Maintenance::EBranch m_eBranch; - int m_iPrefixLen; + Maintenance::EBranch m_branch; + int m_prefixLen; protected: - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void AddMessage(Message::EKind kind, const char* text); public: virtual void Run(); - void SetBranch(Maintenance::EBranch eBranch) { m_eBranch = eBranch; } + void SetBranch(Maintenance::EBranch branch) { m_branch = branch; } }; class UpdateInfoScriptController : public ScriptController { private: - int m_iPrefixLen; - StringBuilder m_UpdateInfo; + int m_prefixLen; + StringBuilder m_updateInfo; protected: - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void AddMessage(Message::EKind kind, const char* text); public: - static void ExecuteScript(const char* szScript, char** pUpdateInfo); + static void ExecuteScript(const char* script, char** updateInfo); }; #endif diff --git a/daemon/main/Options.cpp b/daemon/main/Options.cpp index 2c2edde0..7fd94fdf 100644 --- a/daemon/main/Options.cpp +++ b/daemon/main/Options.cpp @@ -196,65 +196,65 @@ Options* g_pOptions = NULL; Options::OptEntry::OptEntry() { - m_szName = NULL; - m_szValue = NULL; - m_szDefValue = NULL; - m_iLineNo = 0; + m_name = NULL; + m_value = NULL; + m_defValue = NULL; + m_lineNo = 0; } -Options::OptEntry::OptEntry(const char* szName, const char* szValue) +Options::OptEntry::OptEntry(const char* name, const char* value) { - m_szName = strdup(szName); - m_szValue = strdup(szValue); - m_szDefValue = NULL; - m_iLineNo = 0; + m_name = strdup(name); + m_value = strdup(value); + m_defValue = NULL; + m_lineNo = 0; } Options::OptEntry::~OptEntry() { - free(m_szName); - free(m_szValue); - free(m_szDefValue); + free(m_name); + free(m_value); + free(m_defValue); } -void Options::OptEntry::SetName(const char* szName) +void Options::OptEntry::SetName(const char* name) { - free(m_szName); - m_szName = strdup(szName); + free(m_name); + m_name = strdup(name); } -void Options::OptEntry::SetValue(const char* szValue) +void Options::OptEntry::SetValue(const char* value) { - free(m_szValue); - m_szValue = strdup(szValue); + free(m_value); + m_value = strdup(value); - if (!m_szDefValue) + if (!m_defValue) { - m_szDefValue = strdup(szValue); + m_defValue = strdup(value); } } bool Options::OptEntry::Restricted() { - char szLoName[256]; - strncpy(szLoName, m_szName, sizeof(szLoName)); - szLoName[256-1] = '\0'; - for (char* p = szLoName; *p; p++) *p = tolower(*p); // convert string to lowercase + char loName[256]; + strncpy(loName, m_name, sizeof(loName)); + loName[256-1] = '\0'; + for (char* p = loName; *p; p++) *p = tolower(*p); // convert string to lowercase - bool bRestricted = !strcasecmp(m_szName, OPTION_CONTROLIP) || - !strcasecmp(m_szName, OPTION_CONTROLPORT) || - !strcasecmp(m_szName, OPTION_SECURECONTROL) || - !strcasecmp(m_szName, OPTION_SECUREPORT) || - !strcasecmp(m_szName, OPTION_SECURECERT) || - !strcasecmp(m_szName, OPTION_SECUREKEY) || - !strcasecmp(m_szName, OPTION_AUTHORIZEDIP) || - !strcasecmp(m_szName, OPTION_DAEMONUSERNAME) || - !strcasecmp(m_szName, OPTION_UMASK) || - strchr(m_szName, ':') || // All extension script options - strstr(szLoName, "username") || // ServerX.Username, ControlUsername, etc. - strstr(szLoName, "password"); // ServerX.Password, ControlPassword, etc. + bool restricted = !strcasecmp(m_name, OPTION_CONTROLIP) || + !strcasecmp(m_name, OPTION_CONTROLPORT) || + !strcasecmp(m_name, OPTION_SECURECONTROL) || + !strcasecmp(m_name, OPTION_SECUREPORT) || + !strcasecmp(m_name, OPTION_SECURECERT) || + !strcasecmp(m_name, OPTION_SECUREKEY) || + !strcasecmp(m_name, OPTION_AUTHORIZEDIP) || + !strcasecmp(m_name, OPTION_DAEMONUSERNAME) || + !strcasecmp(m_name, OPTION_UMASK) || + strchr(m_name, ':') || // All extension script options + strstr(loName, "username") || // ServerX.Username, ControlUsername, etc. + strstr(loName, "password"); // ServerX.Password, ControlPassword, etc. - return bRestricted; + return restricted; } Options::OptEntries::~OptEntries() @@ -265,19 +265,19 @@ Options::OptEntries::~OptEntries() } } -Options::OptEntry* Options::OptEntries::FindOption(const char* szName) +Options::OptEntry* Options::OptEntries::FindOption(const char* name) { - if (!szName) + if (!name) { return NULL; } for (iterator it = begin(); it != end(); it++) { - OptEntry* pOptEntry = *it; - if (!strcasecmp(pOptEntry->GetName(), szName)) + OptEntry* optEntry = *it; + if (!strcasecmp(optEntry->GetName(), name)) { - return pOptEntry; + return optEntry; } } @@ -285,21 +285,21 @@ Options::OptEntry* Options::OptEntries::FindOption(const char* szName) } -Options::Category::Category(const char* szName, const char* szDestDir, bool bUnpack, const char* szPostScript) +Options::Category::Category(const char* name, const char* destDir, bool unpack, const char* postScript) { - m_szName = strdup(szName); - m_szDestDir = szDestDir ? strdup(szDestDir) : NULL; - m_bUnpack = bUnpack; - m_szPostScript = szPostScript ? strdup(szPostScript) : NULL; + m_name = strdup(name); + m_destDir = destDir ? strdup(destDir) : NULL; + m_unpack = unpack; + m_postScript = postScript ? strdup(postScript) : NULL; } Options::Category::~Category() { - free(m_szName); - free(m_szDestDir); - free(m_szPostScript); + free(m_name); + free(m_destDir); + free(m_postScript); - for (NameList::iterator it = m_Aliases.begin(); it != m_Aliases.end(); it++) + for (NameList::iterator it = m_aliases.begin(); it != m_aliases.end(); it++) { free(*it); } @@ -313,34 +313,34 @@ Options::Categories::~Categories() } } -Options::Category* Options::Categories::FindCategory(const char* szName, bool bSearchAliases) +Options::Category* Options::Categories::FindCategory(const char* name, bool searchAliases) { - if (!szName) + if (!name) { return NULL; } for (iterator it = begin(); it != end(); it++) { - Category* pCategory = *it; - if (!strcasecmp(pCategory->GetName(), szName)) + Category* category = *it; + if (!strcasecmp(category->GetName(), name)) { - return pCategory; + return category; } } - if (bSearchAliases) + if (searchAliases) { for (iterator it = begin(); it != end(); it++) { - Category* pCategory = *it; - for (NameList::iterator it2 = pCategory->GetAliases()->begin(); it2 != pCategory->GetAliases()->end(); it2++) + Category* category = *it; + for (NameList::iterator it2 = category->GetAliases()->begin(); it2 != category->GetAliases()->end(); it2++) { - const char* szAlias = *it2; - WildMask mask(szAlias); - if (mask.Match(szName)) + const char* alias = *it2; + WildMask mask(alias); + if (mask.Match(name)) { - return pCategory; + return category; } } } @@ -350,177 +350,177 @@ Options::Category* Options::Categories::FindCategory(const char* szName, bool bS } -Options::Options(const char* szExeName, const char* szConfigFilename, bool bNoConfig, - CmdOptList* pCommandLineOptions, Extender* pExtender) +Options::Options(const char* exeName, const char* configFilename, bool noConfig, + CmdOptList* commandLineOptions, Extender* extender) { - Init(szExeName, szConfigFilename, bNoConfig, pCommandLineOptions, false, pExtender); + Init(exeName, configFilename, noConfig, commandLineOptions, false, extender); } -Options::Options(CmdOptList* pCommandLineOptions, Extender* pExtender) +Options::Options(CmdOptList* commandLineOptions, Extender* extender) { - Init("nzbget/nzbget", NULL, true, pCommandLineOptions, true, pExtender); + Init("nzbget/nzbget", NULL, true, commandLineOptions, true, extender); } -void Options::Init(const char* szExeName, const char* szConfigFilename, bool bNoConfig, - CmdOptList* pCommandLineOptions, bool bNoDiskAccess, Extender* pExtender) +void Options::Init(const char* exeName, const char* configFilename, bool noConfig, + CmdOptList* commandLineOptions, bool noDiskAccess, Extender* extender) { g_pOptions = this; - m_pExtender = pExtender; - m_bNoDiskAccess = bNoDiskAccess; - m_bNoConfig = bNoConfig; - m_bConfigErrors = false; - m_iConfigLine = 0; - m_bServerMode = false; - m_bRemoteClientMode = false; - m_bFatalError = false; + m_extender = extender; + m_noDiskAccess = noDiskAccess; + m_noConfig = noConfig; + m_configErrors = false; + m_configLine = 0; + m_serverMode = false; + m_remoteClientMode = false; + m_fatalError = false; // initialize options with default values - m_szConfigFilename = NULL; - m_szAppDir = NULL; - m_szDestDir = NULL; - m_szInterDir = NULL; - m_szTempDir = NULL; - m_szQueueDir = NULL; - m_szNzbDir = NULL; - m_szWebDir = NULL; - m_szConfigTemplate = NULL; - m_szScriptDir = NULL; - m_szRequiredDir = NULL; - m_eInfoTarget = mtScreen; - m_eWarningTarget = mtScreen; - m_eErrorTarget = mtScreen; - m_eDebugTarget = mtScreen; - m_eDetailTarget = mtScreen; - m_bDecode = true; - m_bPauseDownload = false; - m_bPausePostProcess = false; - m_bPauseScan = false; - m_bTempPauseDownload = true; - m_bTempPausePostprocess = true; - m_bBrokenLog = false; - m_bNzbLog = false; - m_iDownloadRate = 0; - m_iArticleTimeout = 0; - m_iUrlTimeout = 0; - m_iTerminateTimeout = 0; - m_bAppendCategoryDir = false; - m_bContinuePartial = false; - m_bSaveQueue = false; - m_bFlushQueue = false; - m_bDupeCheck = false; - m_iRetries = 0; - m_iRetryInterval = 0; - m_iControlPort = 0; - m_szControlIP = NULL; - m_szControlUsername = NULL; - m_szControlPassword = NULL; - m_szRestrictedUsername = NULL; - m_szRestrictedPassword = NULL; - m_szAddUsername = NULL; - m_szAddPassword = NULL; - m_bSecureControl = false; - m_iSecurePort = 0; - m_szSecureCert = NULL; - m_szSecureKey = NULL; - m_szAuthorizedIP = NULL; - m_szLockFile = NULL; - m_szDaemonUsername = NULL; - m_eOutputMode = omLoggable; - m_bReloadQueue = false; - m_iUrlConnections = 0; - m_iLogBufferSize = 0; - m_eWriteLog = wlAppend; - m_iRotateLog = 0; - m_szLogFile = NULL; - m_eParCheck = pcManual; - m_bParRepair = false; - m_eParScan = psLimited; - m_bParQuick = true; - m_bParRename = false; - m_iParBuffer = 0; - m_iParThreads = 0; - m_eHealthCheck = hcNone; - m_szScriptOrder = NULL; - m_szPostScript = NULL; - m_szScanScript = NULL; - m_szQueueScript = NULL; - m_szFeedScript = NULL; - m_iUMask = 0; - m_iUpdateInterval = 0; - m_bCursesNZBName = false; - m_bCursesTime = false; - m_bCursesGroup = false; - m_bCrcCheck = false; - m_bDirectWrite = false; - m_iWriteBuffer = 0; - m_iNzbDirInterval = 0; - m_iNzbDirFileAge = 0; - m_bParCleanupQueue = false; - m_iDiskSpace = 0; - m_bTLS = false; - m_bDumpCore = false; - m_bParPauseQueue = false; - m_bScriptPauseQueue = false; - m_bNzbCleanupDisk = false; - m_bDeleteCleanupDisk = false; - m_iParTimeLimit = 0; - m_iKeepHistory = 0; - m_bAccurateRate = false; - m_tResumeTime = 0; - m_bUnpack = false; - m_bUnpackCleanupDisk = false; - m_szUnrarCmd = NULL; - m_szSevenZipCmd = NULL; - m_szUnpackPassFile = NULL; - m_bUnpackPauseQueue = false; - m_szExtCleanupDisk = NULL; - m_szParIgnoreExt = NULL; - m_iFeedHistory = 0; - m_bUrlForce = false; - m_iTimeCorrection = 0; - m_iLocalTimeOffset = 0; - m_iPropagationDelay = 0; - m_iArticleCache = 0; - m_iEventInterval = 0; + m_configFilename = NULL; + m_appDir = NULL; + m_destDir = NULL; + m_interDir = NULL; + m_tempDir = NULL; + m_queueDir = NULL; + m_nzbDir = NULL; + m_webDir = NULL; + m_configTemplate = NULL; + m_scriptDir = NULL; + m_requiredDir = NULL; + m_infoTarget = mtScreen; + m_warningTarget = mtScreen; + m_errorTarget = mtScreen; + m_debugTarget = mtScreen; + m_detailTarget = mtScreen; + m_decode = true; + m_pauseDownload = false; + m_pausePostProcess = false; + m_pauseScan = false; + m_tempPauseDownload = true; + m_tempPausePostprocess = true; + m_brokenLog = false; + m_nzbLog = false; + m_downloadRate = 0; + m_articleTimeout = 0; + m_urlTimeout = 0; + m_terminateTimeout = 0; + m_appendCategoryDir = false; + m_continuePartial = false; + m_saveQueue = false; + m_flushQueue = false; + m_dupeCheck = false; + m_retries = 0; + m_retryInterval = 0; + m_controlPort = 0; + m_controlIP = NULL; + m_controlUsername = NULL; + m_controlPassword = NULL; + m_restrictedUsername = NULL; + m_restrictedPassword = NULL; + m_addUsername = NULL; + m_addPassword = NULL; + m_secureControl = false; + m_securePort = 0; + m_secureCert = NULL; + m_secureKey = NULL; + m_authorizedIP = NULL; + m_lockFile = NULL; + m_daemonUsername = NULL; + m_outputMode = omLoggable; + m_reloadQueue = false; + m_urlConnections = 0; + m_logBufferSize = 0; + m_writeLog = wlAppend; + m_rotateLog = 0; + m_logFile = NULL; + m_parCheck = pcManual; + m_parRepair = false; + m_parScan = psLimited; + m_parQuick = true; + m_parRename = false; + m_parBuffer = 0; + m_parThreads = 0; + m_healthCheck = hcNone; + m_scriptOrder = NULL; + m_postScript = NULL; + m_scanScript = NULL; + m_queueScript = NULL; + m_feedScript = NULL; + m_uMask = 0; + m_updateInterval = 0; + m_cursesNzbName = false; + m_cursesTime = false; + m_cursesGroup = false; + m_crcCheck = false; + m_directWrite = false; + m_writeBuffer = 0; + m_nzbDirInterval = 0; + m_nzbDirFileAge = 0; + m_parCleanupQueue = false; + m_diskSpace = 0; + m_tLS = false; + m_dumpCore = false; + m_parPauseQueue = false; + m_scriptPauseQueue = false; + m_nzbCleanupDisk = false; + m_deleteCleanupDisk = false; + m_parTimeLimit = 0; + m_keepHistory = 0; + m_accurateRate = false; + m_resumeTime = 0; + m_unpack = false; + m_unpackCleanupDisk = false; + m_unrarCmd = NULL; + m_sevenZipCmd = NULL; + m_unpackPassFile = NULL; + m_unpackPauseQueue = false; + m_extCleanupDisk = NULL; + m_parIgnoreExt = NULL; + m_feedHistory = 0; + m_urlForce = false; + m_timeCorrection = 0; + m_localTimeOffset = 0; + m_propagationDelay = 0; + m_articleCache = 0; + m_eventInterval = 0; - m_bNoDiskAccess = bNoDiskAccess; + m_noDiskAccess = noDiskAccess; - m_szConfigFilename = szConfigFilename ? strdup(szConfigFilename) : NULL; + m_configFilename = configFilename ? strdup(configFilename) : NULL; SetOption(OPTION_CONFIGFILE, ""); - char szFilename[MAX_PATH + 1]; - if (m_bNoDiskAccess) + char filename[MAX_PATH + 1]; + if (m_noDiskAccess) { - strncpy(szFilename, szExeName, sizeof(szFilename)); - szFilename[sizeof(szFilename)-1] = '\0'; + strncpy(filename, exeName, sizeof(filename)); + filename[sizeof(filename)-1] = '\0'; } else { - Util::GetExeFileName(szExeName, szFilename, sizeof(szFilename)); + Util::GetExeFileName(exeName, filename, sizeof(filename)); } - Util::NormalizePathSeparators(szFilename); - SetOption(OPTION_APPBIN, szFilename); - char* end = strrchr(szFilename, PATH_SEPARATOR); + Util::NormalizePathSeparators(filename); + SetOption(OPTION_APPBIN, filename); + char* end = strrchr(filename, PATH_SEPARATOR); if (end) *end = '\0'; - SetOption(OPTION_APPDIR, szFilename); - m_szAppDir = strdup(szFilename); + SetOption(OPTION_APPDIR, filename); + m_appDir = strdup(filename); SetOption(OPTION_VERSION, Util::VersionRevision()); InitDefaults(); InitOptFile(); - if (m_bFatalError) + if (m_fatalError) { return; } - if (pCommandLineOptions) + if (commandLineOptions) { - InitCommandLineOptions(pCommandLineOptions); + InitCommandLineOptions(commandLineOptions); } - if (!m_szConfigFilename && !bNoConfig) + if (!m_configFilename && !noConfig) { printf("No configuration-file found\n"); #ifdef WIN32 @@ -528,12 +528,12 @@ void Options::Init(const char* szExeName, const char* szConfigFilename, bool bNo #else printf("Please use option \"-c\" or put configuration-file in one of the following locations:\n"); int p = 0; - while (const char* szFilename = PossibleConfigLocations[p++]) + while (const char* filename = PossibleConfigLocations[p++]) { - printf("%s\n", szFilename); + printf("%s\n", filename); } #endif - m_bFatalError = true; + m_fatalError = true; return; } @@ -549,48 +549,48 @@ void Options::Init(const char* szExeName, const char* szConfigFilename, bool bNo Options::~Options() { g_pOptions = NULL; - free(m_szConfigFilename); - free(m_szAppDir); - free(m_szDestDir); - free(m_szInterDir); - free(m_szTempDir); - free(m_szQueueDir); - free(m_szNzbDir); - free(m_szWebDir); - free(m_szConfigTemplate); - free(m_szScriptDir); - free(m_szRequiredDir); - free(m_szControlIP); - free(m_szControlUsername); - free(m_szControlPassword); - free(m_szRestrictedUsername); - free(m_szRestrictedPassword); - free(m_szAddUsername); - free(m_szAddPassword); - free(m_szSecureCert); - free(m_szSecureKey); - free(m_szAuthorizedIP); - free(m_szLogFile); - free(m_szLockFile); - free(m_szDaemonUsername); - free(m_szScriptOrder); - free(m_szPostScript); - free(m_szScanScript); - free(m_szQueueScript); - free(m_szFeedScript); - free(m_szUnrarCmd); - free(m_szSevenZipCmd); - free(m_szUnpackPassFile); - free(m_szExtCleanupDisk); - free(m_szParIgnoreExt); + free(m_configFilename); + free(m_appDir); + free(m_destDir); + free(m_interDir); + free(m_tempDir); + free(m_queueDir); + free(m_nzbDir); + free(m_webDir); + free(m_configTemplate); + free(m_scriptDir); + free(m_requiredDir); + free(m_controlIP); + free(m_controlUsername); + free(m_controlPassword); + free(m_restrictedUsername); + free(m_restrictedPassword); + free(m_addUsername); + free(m_addPassword); + free(m_secureCert); + free(m_secureKey); + free(m_authorizedIP); + free(m_logFile); + free(m_lockFile); + free(m_daemonUsername); + free(m_scriptOrder); + free(m_postScript); + free(m_scanScript); + free(m_queueScript); + free(m_feedScript); + free(m_unrarCmd); + free(m_sevenZipCmd); + free(m_unpackPassFile); + free(m_extCleanupDisk); + free(m_parIgnoreExt); } void Options::Dump() { - for (OptEntries::iterator it = m_OptEntries.begin(); it != m_OptEntries.end(); it++) + for (OptEntries::iterator it = m_optEntries.begin(); it != m_optEntries.end(); it++) { - OptEntry* pOptEntry = *it; - printf("%s = \"%s\"\n", pOptEntry->GetName(), pOptEntry->GetValue()); + OptEntry* optEntry = *it; + printf("%s = \"%s\"\n", optEntry->GetName(), optEntry->GetValue()); } } @@ -604,10 +604,10 @@ void Options::ConfigError(const char* msg, ...) tmp2[1024-1] = '\0'; va_end(ap); - printf("%s(%i): %s\n", m_szConfigFilename ? Util::BaseFileName(m_szConfigFilename) : "", m_iConfigLine, tmp2); - error("%s(%i): %s", m_szConfigFilename ? Util::BaseFileName(m_szConfigFilename) : "", m_iConfigLine, tmp2); + printf("%s(%i): %s\n", m_configFilename ? Util::BaseFileName(m_configFilename) : "", m_configLine, tmp2); + error("%s(%i): %s", m_configFilename ? Util::BaseFileName(m_configFilename) : "", m_configLine, tmp2); - m_bConfigErrors = true; + m_configErrors = true; } void Options::ConfigWarn(const char* msg, ...) @@ -620,20 +620,20 @@ void Options::ConfigWarn(const char* msg, ...) tmp2[1024-1] = '\0'; va_end(ap); - printf("%s(%i): %s\n", Util::BaseFileName(m_szConfigFilename), m_iConfigLine, tmp2); - warn("%s(%i): %s", Util::BaseFileName(m_szConfigFilename), m_iConfigLine, tmp2); + printf("%s(%i): %s\n", Util::BaseFileName(m_configFilename), m_configLine, tmp2); + warn("%s(%i): %s", Util::BaseFileName(m_configFilename), m_configLine, tmp2); } -void Options::LocateOptionSrcPos(const char *szOptionName) +void Options::LocateOptionSrcPos(const char *optionName) { - OptEntry* pOptEntry = FindOption(szOptionName); - if (pOptEntry) + OptEntry* optEntry = FindOption(optionName); + if (optEntry) { - m_iConfigLine = pOptEntry->GetLineNo(); + m_configLine = optEntry->GetLineNo(); } else { - m_iConfigLine = 0; + m_configLine = 0; } } @@ -752,55 +752,55 @@ void Options::InitDefaults() void Options::InitOptFile() { - if (!m_szConfigFilename && !m_bNoConfig) + if (!m_configFilename && !m_noConfig) { // search for config file in default locations #ifdef WIN32 - char szFilename[MAX_PATH + 20]; - snprintf(szFilename, sizeof(szFilename), "%s\\nzbget.conf", m_szAppDir); + char filename[MAX_PATH + 20]; + snprintf(filename, sizeof(filename), "%s\\nzbget.conf", m_appDir); - if (!Util::FileExists(szFilename)) + if (!Util::FileExists(filename)) { - char szAppDataPath[MAX_PATH]; - SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szAppDataPath); - snprintf(szFilename, sizeof(szFilename), "%s\\NZBGet\\nzbget.conf", szAppDataPath); - szFilename[sizeof(szFilename)-1] = '\0'; + char appDataPath[MAX_PATH]; + SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, appDataPath); + snprintf(filename, sizeof(filename), "%s\\NZBGet\\nzbget.conf", appDataPath); + filename[sizeof(filename)-1] = '\0'; - if (m_pExtender && !Util::FileExists(szFilename)) + if (m_extender && !Util::FileExists(filename)) { - m_pExtender->SetupFirstStart(); + m_extender->SetupFirstStart(); } } - if (Util::FileExists(szFilename)) + if (Util::FileExists(filename)) { - m_szConfigFilename = strdup(szFilename); + m_configFilename = strdup(filename); } #else // look in the exe-directory first - char szFilename[1024]; - snprintf(szFilename, sizeof(szFilename), "%s/nzbget.conf", m_szAppDir); - szFilename[1024-1] = '\0'; + char filename[1024]; + snprintf(filename, sizeof(filename), "%s/nzbget.conf", m_appDir); + filename[1024-1] = '\0'; - if (Util::FileExists(szFilename)) + if (Util::FileExists(filename)) { - m_szConfigFilename = strdup(szFilename); + m_configFilename = strdup(filename); } else { int p = 0; - while (const char* szFilename = PossibleConfigLocations[p++]) + while (const char* filename = PossibleConfigLocations[p++]) { // substitute HOME-variable - char szExpandedFilename[1024]; - if (Util::ExpandHomePath(szFilename, szExpandedFilename, sizeof(szExpandedFilename))) + char expandedFilename[1024]; + if (Util::ExpandHomePath(filename, expandedFilename, sizeof(expandedFilename))) { - szFilename = szExpandedFilename; + filename = expandedFilename; } - if (Util::FileExists(szFilename)) + if (Util::FileExists(filename)) { - m_szConfigFilename = strdup(szFilename); + m_configFilename = strdup(filename); break; } } @@ -808,37 +808,37 @@ void Options::InitOptFile() #endif } - if (m_szConfigFilename) + if (m_configFilename) { // normalize path in filename - char szFilename[MAX_PATH + 1]; - Util::ExpandFileName(m_szConfigFilename, szFilename, sizeof(szFilename)); - szFilename[MAX_PATH] = '\0'; + char filename[MAX_PATH + 1]; + Util::ExpandFileName(m_configFilename, filename, sizeof(filename)); + filename[MAX_PATH] = '\0'; #ifndef WIN32 // substitute HOME-variable - char szExpandedFilename[1024]; - if (Util::ExpandHomePath(szFilename, szExpandedFilename, sizeof(szExpandedFilename))) + char expandedFilename[1024]; + if (Util::ExpandHomePath(filename, expandedFilename, sizeof(expandedFilename))) { - strncpy(szFilename, szExpandedFilename, sizeof(szFilename)); + strncpy(filename, expandedFilename, sizeof(filename)); } #endif - free(m_szConfigFilename); - m_szConfigFilename = strdup(szFilename); + free(m_configFilename); + m_configFilename = strdup(filename); - SetOption(OPTION_CONFIGFILE, m_szConfigFilename); + SetOption(OPTION_CONFIGFILE, m_configFilename); LoadConfigFile(); } } -void Options::CheckDir(char** dir, const char* szOptionName, - const char* szParentDir, bool bAllowEmpty, bool bCreate) +void Options::CheckDir(char** dir, const char* optionName, + const char* parentDir, bool allowEmpty, bool create) { char* usedir = NULL; - const char* tempdir = GetOption(szOptionName); + const char* tempdir = GetOption(optionName); - if (m_bNoDiskAccess) + if (m_noDiskAccess) { *dir = strdup(tempdir); return; @@ -846,9 +846,9 @@ void Options::CheckDir(char** dir, const char* szOptionName, if (Util::EmptyStr(tempdir)) { - if (!bAllowEmpty) + if (!allowEmpty) { - ConfigError("Invalid value for option \"%s\": ", szOptionName); + ConfigError("Invalid value for option \"%s\": ", optionName); } *dir = strdup(""); return; @@ -867,19 +867,19 @@ void Options::CheckDir(char** dir, const char* szOptionName, if (!(usedir[0] == PATH_SEPARATOR || usedir[0] == ALT_PATH_SEPARATOR || (usedir[0] && usedir[1] == ':')) && - !Util::EmptyStr(szParentDir)) + !Util::EmptyStr(parentDir)) { // convert relative path to absolute path - int plen = strlen(szParentDir); + int plen = strlen(parentDir); int len2 = len + plen + 4; char* usedir2 = (char*)malloc(len2); - if (szParentDir[plen-1] == PATH_SEPARATOR || szParentDir[plen-1] == ALT_PATH_SEPARATOR) + if (parentDir[plen-1] == PATH_SEPARATOR || parentDir[plen-1] == ALT_PATH_SEPARATOR) { - snprintf(usedir2, len2, "%s%s", szParentDir, usedir); + snprintf(usedir2, len2, "%s%s", parentDir, usedir); } else { - snprintf(usedir2, len2, "%s%c%s", szParentDir, PATH_SEPARATOR, usedir); + snprintf(usedir2, len2, "%s%c%s", parentDir, PATH_SEPARATOR, usedir); } usedir2[len2-1] = '\0'; free(usedir); @@ -889,178 +889,178 @@ void Options::CheckDir(char** dir, const char* szOptionName, int ulen = strlen(usedir); usedir[ulen-1] = '\0'; - SetOption(szOptionName, usedir); + SetOption(optionName, usedir); usedir[ulen-1] = PATH_SEPARATOR; } // Ensure the dir is created - char szErrBuf[1024]; - if (bCreate && !Util::ForceDirectories(usedir, szErrBuf, sizeof(szErrBuf))) + char errBuf[1024]; + if (create && !Util::ForceDirectories(usedir, errBuf, sizeof(errBuf))) { - ConfigError("Invalid value for option \"%s\" (%s): %s", szOptionName, usedir, szErrBuf); + ConfigError("Invalid value for option \"%s\" (%s): %s", optionName, usedir, errBuf); } *dir = usedir; } void Options::InitOptions() { - const char* szMainDir = GetOption(OPTION_MAINDIR); + const char* mainDir = GetOption(OPTION_MAINDIR); - CheckDir(&m_szDestDir, OPTION_DESTDIR, szMainDir, false, false); - CheckDir(&m_szInterDir, OPTION_INTERDIR, szMainDir, true, false); - CheckDir(&m_szTempDir, OPTION_TEMPDIR, szMainDir, false, true); - CheckDir(&m_szQueueDir, OPTION_QUEUEDIR, szMainDir, false, true); - CheckDir(&m_szWebDir, OPTION_WEBDIR, NULL, true, false); - CheckDir(&m_szScriptDir, OPTION_SCRIPTDIR, szMainDir, true, false); - CheckDir(&m_szNzbDir, OPTION_NZBDIR, szMainDir, false, true); + CheckDir(&m_destDir, OPTION_DESTDIR, mainDir, false, false); + CheckDir(&m_interDir, OPTION_INTERDIR, mainDir, true, false); + CheckDir(&m_tempDir, OPTION_TEMPDIR, mainDir, false, true); + CheckDir(&m_queueDir, OPTION_QUEUEDIR, mainDir, false, true); + CheckDir(&m_webDir, OPTION_WEBDIR, NULL, true, false); + CheckDir(&m_scriptDir, OPTION_SCRIPTDIR, mainDir, true, false); + CheckDir(&m_nzbDir, OPTION_NZBDIR, mainDir, false, true); - m_szRequiredDir = strdup(GetOption(OPTION_REQUIREDDIR)); + m_requiredDir = strdup(GetOption(OPTION_REQUIREDDIR)); - m_szConfigTemplate = strdup(GetOption(OPTION_CONFIGTEMPLATE)); - m_szScriptOrder = strdup(GetOption(OPTION_SCRIPTORDER)); - m_szPostScript = strdup(GetOption(OPTION_POSTSCRIPT)); - m_szScanScript = strdup(GetOption(OPTION_SCANSCRIPT)); - m_szQueueScript = strdup(GetOption(OPTION_QUEUESCRIPT)); - m_szFeedScript = strdup(GetOption(OPTION_FEEDSCRIPT)); - m_szControlIP = strdup(GetOption(OPTION_CONTROLIP)); - m_szControlUsername = strdup(GetOption(OPTION_CONTROLUSERNAME)); - m_szControlPassword = strdup(GetOption(OPTION_CONTROLPASSWORD)); - m_szRestrictedUsername = strdup(GetOption(OPTION_RESTRICTEDUSERNAME)); - m_szRestrictedPassword = strdup(GetOption(OPTION_RESTRICTEDPASSWORD)); - m_szAddUsername = strdup(GetOption(OPTION_ADDUSERNAME)); - m_szAddPassword = strdup(GetOption(OPTION_ADDPASSWORD)); - m_szSecureCert = strdup(GetOption(OPTION_SECURECERT)); - m_szSecureKey = strdup(GetOption(OPTION_SECUREKEY)); - m_szAuthorizedIP = strdup(GetOption(OPTION_AUTHORIZEDIP)); - m_szLockFile = strdup(GetOption(OPTION_LOCKFILE)); - m_szDaemonUsername = strdup(GetOption(OPTION_DAEMONUSERNAME)); - m_szLogFile = strdup(GetOption(OPTION_LOGFILE)); - m_szUnrarCmd = strdup(GetOption(OPTION_UNRARCMD)); - m_szSevenZipCmd = strdup(GetOption(OPTION_SEVENZIPCMD)); - m_szUnpackPassFile = strdup(GetOption(OPTION_UNPACKPASSFILE)); - m_szExtCleanupDisk = strdup(GetOption(OPTION_EXTCLEANUPDISK)); - m_szParIgnoreExt = strdup(GetOption(OPTION_PARIGNOREEXT)); + m_configTemplate = strdup(GetOption(OPTION_CONFIGTEMPLATE)); + m_scriptOrder = strdup(GetOption(OPTION_SCRIPTORDER)); + m_postScript = strdup(GetOption(OPTION_POSTSCRIPT)); + m_scanScript = strdup(GetOption(OPTION_SCANSCRIPT)); + m_queueScript = strdup(GetOption(OPTION_QUEUESCRIPT)); + m_feedScript = strdup(GetOption(OPTION_FEEDSCRIPT)); + m_controlIP = strdup(GetOption(OPTION_CONTROLIP)); + m_controlUsername = strdup(GetOption(OPTION_CONTROLUSERNAME)); + m_controlPassword = strdup(GetOption(OPTION_CONTROLPASSWORD)); + m_restrictedUsername = strdup(GetOption(OPTION_RESTRICTEDUSERNAME)); + m_restrictedPassword = strdup(GetOption(OPTION_RESTRICTEDPASSWORD)); + m_addUsername = strdup(GetOption(OPTION_ADDUSERNAME)); + m_addPassword = strdup(GetOption(OPTION_ADDPASSWORD)); + m_secureCert = strdup(GetOption(OPTION_SECURECERT)); + m_secureKey = strdup(GetOption(OPTION_SECUREKEY)); + m_authorizedIP = strdup(GetOption(OPTION_AUTHORIZEDIP)); + m_lockFile = strdup(GetOption(OPTION_LOCKFILE)); + m_daemonUsername = strdup(GetOption(OPTION_DAEMONUSERNAME)); + m_logFile = strdup(GetOption(OPTION_LOGFILE)); + m_unrarCmd = strdup(GetOption(OPTION_UNRARCMD)); + m_sevenZipCmd = strdup(GetOption(OPTION_SEVENZIPCMD)); + m_unpackPassFile = strdup(GetOption(OPTION_UNPACKPASSFILE)); + m_extCleanupDisk = strdup(GetOption(OPTION_EXTCLEANUPDISK)); + m_parIgnoreExt = strdup(GetOption(OPTION_PARIGNOREEXT)); - m_iDownloadRate = ParseIntValue(OPTION_DOWNLOADRATE, 10) * 1024; - m_iArticleTimeout = ParseIntValue(OPTION_ARTICLETIMEOUT, 10); - m_iUrlTimeout = ParseIntValue(OPTION_URLTIMEOUT, 10); - m_iTerminateTimeout = ParseIntValue(OPTION_TERMINATETIMEOUT, 10); - m_iRetries = ParseIntValue(OPTION_RETRIES, 10); - m_iRetryInterval = ParseIntValue(OPTION_RETRYINTERVAL, 10); - m_iControlPort = ParseIntValue(OPTION_CONTROLPORT, 10); - m_iSecurePort = ParseIntValue(OPTION_SECUREPORT, 10); - m_iUrlConnections = ParseIntValue(OPTION_URLCONNECTIONS, 10); - m_iLogBufferSize = ParseIntValue(OPTION_LOGBUFFERSIZE, 10); - m_iRotateLog = ParseIntValue(OPTION_ROTATELOG, 10); - m_iUMask = ParseIntValue(OPTION_UMASK, 8); - m_iUpdateInterval = ParseIntValue(OPTION_UPDATEINTERVAL, 10); - m_iWriteBuffer = ParseIntValue(OPTION_WRITEBUFFER, 10); - m_iNzbDirInterval = ParseIntValue(OPTION_NZBDIRINTERVAL, 10); - m_iNzbDirFileAge = ParseIntValue(OPTION_NZBDIRFILEAGE, 10); - m_iDiskSpace = ParseIntValue(OPTION_DISKSPACE, 10); - m_iParTimeLimit = ParseIntValue(OPTION_PARTIMELIMIT, 10); - m_iKeepHistory = ParseIntValue(OPTION_KEEPHISTORY, 10); - m_iFeedHistory = ParseIntValue(OPTION_FEEDHISTORY, 10); - m_iTimeCorrection = ParseIntValue(OPTION_TIMECORRECTION, 10); - if (-24 <= m_iTimeCorrection && m_iTimeCorrection <= 24) + m_downloadRate = ParseIntValue(OPTION_DOWNLOADRATE, 10) * 1024; + m_articleTimeout = ParseIntValue(OPTION_ARTICLETIMEOUT, 10); + m_urlTimeout = ParseIntValue(OPTION_URLTIMEOUT, 10); + m_terminateTimeout = ParseIntValue(OPTION_TERMINATETIMEOUT, 10); + m_retries = ParseIntValue(OPTION_RETRIES, 10); + m_retryInterval = ParseIntValue(OPTION_RETRYINTERVAL, 10); + m_controlPort = ParseIntValue(OPTION_CONTROLPORT, 10); + m_securePort = ParseIntValue(OPTION_SECUREPORT, 10); + m_urlConnections = ParseIntValue(OPTION_URLCONNECTIONS, 10); + m_logBufferSize = ParseIntValue(OPTION_LOGBUFFERSIZE, 10); + m_rotateLog = ParseIntValue(OPTION_ROTATELOG, 10); + m_uMask = ParseIntValue(OPTION_UMASK, 8); + m_updateInterval = ParseIntValue(OPTION_UPDATEINTERVAL, 10); + m_writeBuffer = ParseIntValue(OPTION_WRITEBUFFER, 10); + m_nzbDirInterval = ParseIntValue(OPTION_NZBDIRINTERVAL, 10); + m_nzbDirFileAge = ParseIntValue(OPTION_NZBDIRFILEAGE, 10); + m_diskSpace = ParseIntValue(OPTION_DISKSPACE, 10); + m_parTimeLimit = ParseIntValue(OPTION_PARTIMELIMIT, 10); + m_keepHistory = ParseIntValue(OPTION_KEEPHISTORY, 10); + m_feedHistory = ParseIntValue(OPTION_FEEDHISTORY, 10); + m_timeCorrection = ParseIntValue(OPTION_TIMECORRECTION, 10); + if (-24 <= m_timeCorrection && m_timeCorrection <= 24) { - m_iTimeCorrection *= 60; + m_timeCorrection *= 60; } - m_iTimeCorrection *= 60; - m_iPropagationDelay = ParseIntValue(OPTION_PROPAGATIONDELAY, 10) * 60; - m_iArticleCache = ParseIntValue(OPTION_ARTICLECACHE, 10); - m_iEventInterval = ParseIntValue(OPTION_EVENTINTERVAL, 10); - m_iParBuffer = ParseIntValue(OPTION_PARBUFFER, 10); - m_iParThreads = ParseIntValue(OPTION_PARTHREADS, 10); + m_timeCorrection *= 60; + m_propagationDelay = ParseIntValue(OPTION_PROPAGATIONDELAY, 10) * 60; + m_articleCache = ParseIntValue(OPTION_ARTICLECACHE, 10); + m_eventInterval = ParseIntValue(OPTION_EVENTINTERVAL, 10); + m_parBuffer = ParseIntValue(OPTION_PARBUFFER, 10); + m_parThreads = ParseIntValue(OPTION_PARTHREADS, 10); - m_bBrokenLog = (bool)ParseEnumValue(OPTION_BROKENLOG, BoolCount, BoolNames, BoolValues); - m_bNzbLog = (bool)ParseEnumValue(OPTION_NZBLOG, BoolCount, BoolNames, BoolValues); - m_bAppendCategoryDir = (bool)ParseEnumValue(OPTION_APPENDCATEGORYDIR, BoolCount, BoolNames, BoolValues); - m_bContinuePartial = (bool)ParseEnumValue(OPTION_CONTINUEPARTIAL, BoolCount, BoolNames, BoolValues); - m_bSaveQueue = (bool)ParseEnumValue(OPTION_SAVEQUEUE, BoolCount, BoolNames, BoolValues); - m_bFlushQueue = (bool)ParseEnumValue(OPTION_FLUSHQUEUE, BoolCount, BoolNames, BoolValues); - m_bDupeCheck = (bool)ParseEnumValue(OPTION_DUPECHECK, BoolCount, BoolNames, BoolValues); - m_bParRepair = (bool)ParseEnumValue(OPTION_PARREPAIR, BoolCount, BoolNames, BoolValues); - m_bParQuick = (bool)ParseEnumValue(OPTION_PARQUICK, BoolCount, BoolNames, BoolValues); - m_bParRename = (bool)ParseEnumValue(OPTION_PARRENAME, BoolCount, BoolNames, BoolValues); - m_bReloadQueue = (bool)ParseEnumValue(OPTION_RELOADQUEUE, BoolCount, BoolNames, BoolValues); - m_bCursesNZBName = (bool)ParseEnumValue(OPTION_CURSESNZBNAME, BoolCount, BoolNames, BoolValues); - m_bCursesTime = (bool)ParseEnumValue(OPTION_CURSESTIME, BoolCount, BoolNames, BoolValues); - m_bCursesGroup = (bool)ParseEnumValue(OPTION_CURSESGROUP, BoolCount, BoolNames, BoolValues); - m_bCrcCheck = (bool)ParseEnumValue(OPTION_CRCCHECK, BoolCount, BoolNames, BoolValues); - m_bDirectWrite = (bool)ParseEnumValue(OPTION_DIRECTWRITE, BoolCount, BoolNames, BoolValues); - m_bParCleanupQueue = (bool)ParseEnumValue(OPTION_PARCLEANUPQUEUE, BoolCount, BoolNames, BoolValues); - m_bDecode = (bool)ParseEnumValue(OPTION_DECODE, BoolCount, BoolNames, BoolValues); - m_bDumpCore = (bool)ParseEnumValue(OPTION_DUMPCORE, BoolCount, BoolNames, BoolValues); - m_bParPauseQueue = (bool)ParseEnumValue(OPTION_PARPAUSEQUEUE, BoolCount, BoolNames, BoolValues); - m_bScriptPauseQueue = (bool)ParseEnumValue(OPTION_SCRIPTPAUSEQUEUE, BoolCount, BoolNames, BoolValues); - m_bNzbCleanupDisk = (bool)ParseEnumValue(OPTION_NZBCLEANUPDISK, BoolCount, BoolNames, BoolValues); - m_bDeleteCleanupDisk = (bool)ParseEnumValue(OPTION_DELETECLEANUPDISK, BoolCount, BoolNames, BoolValues); - m_bAccurateRate = (bool)ParseEnumValue(OPTION_ACCURATERATE, BoolCount, BoolNames, BoolValues); - m_bSecureControl = (bool)ParseEnumValue(OPTION_SECURECONTROL, BoolCount, BoolNames, BoolValues); - m_bUnpack = (bool)ParseEnumValue(OPTION_UNPACK, BoolCount, BoolNames, BoolValues); - m_bUnpackCleanupDisk = (bool)ParseEnumValue(OPTION_UNPACKCLEANUPDISK, BoolCount, BoolNames, BoolValues); - m_bUnpackPauseQueue = (bool)ParseEnumValue(OPTION_UNPACKPAUSEQUEUE, BoolCount, BoolNames, BoolValues); - m_bUrlForce = (bool)ParseEnumValue(OPTION_URLFORCE, BoolCount, BoolNames, BoolValues); + m_brokenLog = (bool)ParseEnumValue(OPTION_BROKENLOG, BoolCount, BoolNames, BoolValues); + m_nzbLog = (bool)ParseEnumValue(OPTION_NZBLOG, BoolCount, BoolNames, BoolValues); + m_appendCategoryDir = (bool)ParseEnumValue(OPTION_APPENDCATEGORYDIR, BoolCount, BoolNames, BoolValues); + m_continuePartial = (bool)ParseEnumValue(OPTION_CONTINUEPARTIAL, BoolCount, BoolNames, BoolValues); + m_saveQueue = (bool)ParseEnumValue(OPTION_SAVEQUEUE, BoolCount, BoolNames, BoolValues); + m_flushQueue = (bool)ParseEnumValue(OPTION_FLUSHQUEUE, BoolCount, BoolNames, BoolValues); + m_dupeCheck = (bool)ParseEnumValue(OPTION_DUPECHECK, BoolCount, BoolNames, BoolValues); + m_parRepair = (bool)ParseEnumValue(OPTION_PARREPAIR, BoolCount, BoolNames, BoolValues); + m_parQuick = (bool)ParseEnumValue(OPTION_PARQUICK, BoolCount, BoolNames, BoolValues); + m_parRename = (bool)ParseEnumValue(OPTION_PARRENAME, BoolCount, BoolNames, BoolValues); + m_reloadQueue = (bool)ParseEnumValue(OPTION_RELOADQUEUE, BoolCount, BoolNames, BoolValues); + m_cursesNzbName = (bool)ParseEnumValue(OPTION_CURSESNZBNAME, BoolCount, BoolNames, BoolValues); + m_cursesTime = (bool)ParseEnumValue(OPTION_CURSESTIME, BoolCount, BoolNames, BoolValues); + m_cursesGroup = (bool)ParseEnumValue(OPTION_CURSESGROUP, BoolCount, BoolNames, BoolValues); + m_crcCheck = (bool)ParseEnumValue(OPTION_CRCCHECK, BoolCount, BoolNames, BoolValues); + m_directWrite = (bool)ParseEnumValue(OPTION_DIRECTWRITE, BoolCount, BoolNames, BoolValues); + m_parCleanupQueue = (bool)ParseEnumValue(OPTION_PARCLEANUPQUEUE, BoolCount, BoolNames, BoolValues); + m_decode = (bool)ParseEnumValue(OPTION_DECODE, BoolCount, BoolNames, BoolValues); + m_dumpCore = (bool)ParseEnumValue(OPTION_DUMPCORE, BoolCount, BoolNames, BoolValues); + m_parPauseQueue = (bool)ParseEnumValue(OPTION_PARPAUSEQUEUE, BoolCount, BoolNames, BoolValues); + m_scriptPauseQueue = (bool)ParseEnumValue(OPTION_SCRIPTPAUSEQUEUE, BoolCount, BoolNames, BoolValues); + m_nzbCleanupDisk = (bool)ParseEnumValue(OPTION_NZBCLEANUPDISK, BoolCount, BoolNames, BoolValues); + m_deleteCleanupDisk = (bool)ParseEnumValue(OPTION_DELETECLEANUPDISK, BoolCount, BoolNames, BoolValues); + m_accurateRate = (bool)ParseEnumValue(OPTION_ACCURATERATE, BoolCount, BoolNames, BoolValues); + m_secureControl = (bool)ParseEnumValue(OPTION_SECURECONTROL, BoolCount, BoolNames, BoolValues); + m_unpack = (bool)ParseEnumValue(OPTION_UNPACK, BoolCount, BoolNames, BoolValues); + m_unpackCleanupDisk = (bool)ParseEnumValue(OPTION_UNPACKCLEANUPDISK, BoolCount, BoolNames, BoolValues); + m_unpackPauseQueue = (bool)ParseEnumValue(OPTION_UNPACKPAUSEQUEUE, BoolCount, BoolNames, BoolValues); + m_urlForce = (bool)ParseEnumValue(OPTION_URLFORCE, BoolCount, BoolNames, BoolValues); const char* OutputModeNames[] = { "loggable", "logable", "log", "colored", "color", "ncurses", "curses" }; const int OutputModeValues[] = { omLoggable, omLoggable, omLoggable, omColored, omColored, omNCurses, omNCurses }; const int OutputModeCount = 7; - m_eOutputMode = (EOutputMode)ParseEnumValue(OPTION_OUTPUTMODE, OutputModeCount, OutputModeNames, OutputModeValues); + m_outputMode = (EOutputMode)ParseEnumValue(OPTION_OUTPUTMODE, OutputModeCount, OutputModeNames, OutputModeValues); const char* ParCheckNames[] = { "auto", "always", "force", "manual" }; const int ParCheckValues[] = { pcAuto, pcAlways, pcForce, pcManual }; const int ParCheckCount = 6; - m_eParCheck = (EParCheck)ParseEnumValue(OPTION_PARCHECK, ParCheckCount, ParCheckNames, ParCheckValues); + m_parCheck = (EParCheck)ParseEnumValue(OPTION_PARCHECK, ParCheckCount, ParCheckNames, ParCheckValues); const char* ParScanNames[] = { "limited", "extended", "full", "dupe" }; const int ParScanValues[] = { psLimited, psExtended, psFull, psDupe }; const int ParScanCount = 4; - m_eParScan = (EParScan)ParseEnumValue(OPTION_PARSCAN, ParScanCount, ParScanNames, ParScanValues); + m_parScan = (EParScan)ParseEnumValue(OPTION_PARSCAN, ParScanCount, ParScanNames, ParScanValues); const char* HealthCheckNames[] = { "pause", "delete", "none" }; const int HealthCheckValues[] = { hcPause, hcDelete, hcNone }; const int HealthCheckCount = 3; - m_eHealthCheck = (EHealthCheck)ParseEnumValue(OPTION_HEALTHCHECK, HealthCheckCount, HealthCheckNames, HealthCheckValues); + m_healthCheck = (EHealthCheck)ParseEnumValue(OPTION_HEALTHCHECK, HealthCheckCount, HealthCheckNames, HealthCheckValues); const char* TargetNames[] = { "screen", "log", "both", "none" }; const int TargetValues[] = { mtScreen, mtLog, mtBoth, mtNone }; const int TargetCount = 4; - m_eInfoTarget = (EMessageTarget)ParseEnumValue(OPTION_INFOTARGET, TargetCount, TargetNames, TargetValues); - m_eWarningTarget = (EMessageTarget)ParseEnumValue(OPTION_WARNINGTARGET, TargetCount, TargetNames, TargetValues); - m_eErrorTarget = (EMessageTarget)ParseEnumValue(OPTION_ERRORTARGET, TargetCount, TargetNames, TargetValues); - m_eDebugTarget = (EMessageTarget)ParseEnumValue(OPTION_DEBUGTARGET, TargetCount, TargetNames, TargetValues); - m_eDetailTarget = (EMessageTarget)ParseEnumValue(OPTION_DETAILTARGET, TargetCount, TargetNames, TargetValues); + m_infoTarget = (EMessageTarget)ParseEnumValue(OPTION_INFOTARGET, TargetCount, TargetNames, TargetValues); + m_warningTarget = (EMessageTarget)ParseEnumValue(OPTION_WARNINGTARGET, TargetCount, TargetNames, TargetValues); + m_errorTarget = (EMessageTarget)ParseEnumValue(OPTION_ERRORTARGET, TargetCount, TargetNames, TargetValues); + m_debugTarget = (EMessageTarget)ParseEnumValue(OPTION_DEBUGTARGET, TargetCount, TargetNames, TargetValues); + m_detailTarget = (EMessageTarget)ParseEnumValue(OPTION_DETAILTARGET, TargetCount, TargetNames, TargetValues); const char* WriteLogNames[] = { "none", "append", "reset", "rotate" }; const int WriteLogValues[] = { wlNone, wlAppend, wlReset, wlRotate }; const int WriteLogCount = 4; - m_eWriteLog = (EWriteLog)ParseEnumValue(OPTION_WRITELOG, WriteLogCount, WriteLogNames, WriteLogValues); + m_writeLog = (EWriteLog)ParseEnumValue(OPTION_WRITELOG, WriteLogCount, WriteLogNames, WriteLogValues); } int Options::ParseEnumValue(const char* OptName, int argc, const char * argn[], const int argv[]) { - OptEntry* pOptEntry = FindOption(OptName); - if (!pOptEntry) + OptEntry* optEntry = FindOption(OptName); + if (!optEntry) { ConfigError("Undefined value for option \"%s\"", OptName); return argv[0]; } - int iDefNum = 0; + int defNum = 0; for (int i = 0; i < argc; i++) { - if (!strcasecmp(pOptEntry->GetValue(), argn[i])) + if (!strcasecmp(optEntry->GetValue(), argn[i])) { // normalizing option value in option list, for example "NO" -> "no" for (int j = 0; j < argc; j++) { if (argv[j] == argv[i]) { - if (strcmp(argn[j], pOptEntry->GetValue())) + if (strcmp(argn[j], optEntry->GetValue())) { - pOptEntry->SetValue(argn[j]); + optEntry->SetValue(argn[j]); } break; } @@ -1069,36 +1069,36 @@ int Options::ParseEnumValue(const char* OptName, int argc, const char * argn[], return argv[i]; } - if (!strcasecmp(pOptEntry->GetDefValue(), argn[i])) + if (!strcasecmp(optEntry->GetDefValue(), argn[i])) { - iDefNum = i; + defNum = i; } } - m_iConfigLine = pOptEntry->GetLineNo(); - ConfigError("Invalid value for option \"%s\": \"%s\"", OptName, pOptEntry->GetValue()); - pOptEntry->SetValue(argn[iDefNum]); - return argv[iDefNum]; + m_configLine = optEntry->GetLineNo(); + ConfigError("Invalid value for option \"%s\": \"%s\"", OptName, optEntry->GetValue()); + optEntry->SetValue(argn[defNum]); + return argv[defNum]; } -int Options::ParseIntValue(const char* OptName, int iBase) +int Options::ParseIntValue(const char* OptName, int base) { - OptEntry* pOptEntry = FindOption(OptName); - if (!pOptEntry) + OptEntry* optEntry = FindOption(OptName); + if (!optEntry) { ConfigError("Undefined value for option \"%s\"", OptName); return 0; } char *endptr; - int val = strtol(pOptEntry->GetValue(), &endptr, iBase); + int val = strtol(optEntry->GetValue(), &endptr, base); if (endptr && *endptr != '\0') { - m_iConfigLine = pOptEntry->GetLineNo(); - ConfigError("Invalid value for option \"%s\": \"%s\"", OptName, pOptEntry->GetValue()); - pOptEntry->SetValue(pOptEntry->GetDefValue()); - val = strtol(pOptEntry->GetDefValue(), NULL, iBase); + m_configLine = optEntry->GetLineNo(); + ConfigError("Invalid value for option \"%s\": \"%s\"", OptName, optEntry->GetValue()); + optEntry->SetValue(optEntry->GetDefValue()); + val = strtol(optEntry->GetDefValue(), NULL, base); } return val; @@ -1106,12 +1106,12 @@ int Options::ParseIntValue(const char* OptName, int iBase) void Options::SetOption(const char* optname, const char* value) { - OptEntry* pOptEntry = FindOption(optname); - if (!pOptEntry) + OptEntry* optEntry = FindOption(optname); + if (!optEntry) { - pOptEntry = new OptEntry(); - pOptEntry->SetName(optname); - m_OptEntries.push_back(pOptEntry); + optEntry = new OptEntry(); + optEntry->SetName(optname); + m_optEntries.push_back(optEntry); } char* curvalue = NULL; @@ -1119,18 +1119,18 @@ void Options::SetOption(const char* optname, const char* value) #ifndef WIN32 if (value && (value[0] == '~') && (value[1] == '/')) { - char szExpandedPath[1024]; - if (m_bNoDiskAccess) + char expandedPath[1024]; + if (m_noDiskAccess) { - strncpy(szExpandedPath, value, 1024); - szExpandedPath[1024-1] = '\0'; + strncpy(expandedPath, value, 1024); + expandedPath[1024-1] = '\0'; } - else if (!Util::ExpandHomePath(value, szExpandedPath, sizeof(szExpandedPath))) + else if (!Util::ExpandHomePath(value, expandedPath, sizeof(expandedPath))) { ConfigError("Invalid value for option\"%s\": unable to determine home-directory", optname); - szExpandedPath[0] = '\0'; + expandedPath[0] = '\0'; } - curvalue = strdup(szExpandedPath); + curvalue = strdup(expandedPath); } else #endif @@ -1138,7 +1138,7 @@ void Options::SetOption(const char* optname, const char* value) curvalue = strdup(value); } - pOptEntry->SetLineNo(m_iConfigLine); + optEntry->SetLineNo(m_configLine); // expand variables while (char* dollar = strstr(curvalue, "${")) @@ -1173,34 +1173,34 @@ void Options::SetOption(const char* optname, const char* value) } } - pOptEntry->SetValue(curvalue); + optEntry->SetValue(curvalue); free(curvalue); } Options::OptEntry* Options::FindOption(const char* optname) { - OptEntry* pOptEntry = m_OptEntries.FindOption(optname); + OptEntry* optEntry = m_optEntries.FindOption(optname); // normalize option name in option list; for example "server1.joingroup" -> "Server1.JoinGroup" - if (pOptEntry && strcmp(pOptEntry->GetName(), optname)) + if (optEntry && strcmp(optEntry->GetName(), optname)) { - pOptEntry->SetName(optname); + optEntry->SetName(optname); } - return pOptEntry; + return optEntry; } const char* Options::GetOption(const char* optname) { - OptEntry* pOptEntry = FindOption(optname); - if (pOptEntry) + OptEntry* optEntry = FindOption(optname); + if (optEntry) { - if (pOptEntry->GetLineNo() > 0) + if (optEntry->GetLineNo() > 0) { - m_iConfigLine = pOptEntry->GetLineNo(); + m_configLine = optEntry->GetLineNo(); } - return pOptEntry->GetValue(); + return optEntry->GetValue(); } return NULL; } @@ -1214,10 +1214,10 @@ void Options::InitServers() sprintf(optname, "Server%i.Active", n); const char* nactive = GetOption(optname); - bool bActive = true; + bool active = true; if (nactive) { - bActive = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); + active = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); } sprintf(optname, "Server%i.Name", n); @@ -1243,26 +1243,26 @@ void Options::InitServers() sprintf(optname, "Server%i.JoinGroup", n); const char* njoingroup = GetOption(optname); - bool bJoinGroup = false; + bool joinGroup = false; if (njoingroup) { - bJoinGroup = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); + joinGroup = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); } sprintf(optname, "Server%i.Encryption", n); const char* ntls = GetOption(optname); - bool bTLS = false; + bool tLS = false; if (ntls) { - bTLS = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); + tLS = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); #ifdef DISABLE_TLS - if (bTLS) + if (tLS) { ConfigError("Invalid value for option \"%s\": program was compiled without TLS/SSL-support", optname); - bTLS = false; + tLS = false; } #endif - m_bTLS |= bTLS; + m_tLS |= tLS; } sprintf(optname, "Server%i.Cipher", n); @@ -1285,13 +1285,13 @@ void Options::InitServers() if (completed) { - if (m_pExtender) + if (m_extender) { - m_pExtender->AddNewsServer(n, bActive, nname, + m_extender->AddNewsServer(n, active, nname, nhost, nport ? atoi(nport) : 119, nusername, npassword, - bJoinGroup, bTLS, ncipher, + joinGroup, tLS, ncipher, nconnections ? atoi(nconnections) : 1, nretention ? atoi(nretention) : 0, nlevel ? atoi(nlevel) : 0, @@ -1323,10 +1323,10 @@ void Options::InitCategories() sprintf(optname, "Category%i.Unpack", n); const char* nunpack = GetOption(optname); - bool bUnpack = true; + bool unpack = true; if (nunpack) { - bUnpack = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); + unpack = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); } sprintf(optname, "Category%i.PostScript", n); @@ -1345,24 +1345,24 @@ void Options::InitCategories() if (completed) { - char* szDestDir = NULL; + char* destDir = NULL; if (ndestdir && ndestdir[0] != '\0') { - CheckDir(&szDestDir, destdiroptname, m_szDestDir, false, false); + CheckDir(&destDir, destdiroptname, m_destDir, false, false); } - Category* pCategory = new Category(nname, szDestDir, bUnpack, npostscript); - m_Categories.push_back(pCategory); + Category* category = new Category(nname, destDir, unpack, npostscript); + m_categories.push_back(category); - free(szDestDir); + free(destDir); // split Aliases into tokens and create items for each token if (naliases) { Tokenizer tok(naliases, ",;"); - while (const char* szAliasName = tok.Next()) + while (const char* aliasName = tok.Next()) { - pCategory->GetAliases()->push_back(strdup(szAliasName)); + category->GetAliases()->push_back(strdup(aliasName)); } } } @@ -1399,18 +1399,18 @@ void Options::InitFeeds() sprintf(optname, "Feed%i.Backlog", n); const char* nbacklog = GetOption(optname); - bool bBacklog = true; + bool backlog = true; if (nbacklog) { - bBacklog = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); + backlog = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); } sprintf(optname, "Feed%i.PauseNzb", n); const char* npausenzb = GetOption(optname); - bool bPauseNzb = false; + bool pauseNzb = false; if (npausenzb) { - bPauseNzb = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); + pauseNzb = (bool)ParseEnumValue(optname, BoolCount, BoolNames, BoolValues); } sprintf(optname, "Feed%i.Interval", n); @@ -1430,10 +1430,10 @@ void Options::InitFeeds() if (completed) { - if (m_pExtender) + if (m_extender) { - m_pExtender->AddFeed(n, nname, nurl, ninterval ? atoi(ninterval) : 0, nfilter, - bBacklog, bPauseNzb, ncategory, npriority ? atoi(npriority) : 0, nfeedscript); + m_extender->AddFeed(n, nname, nurl, ninterval ? atoi(ninterval) : 0, nfilter, + backlog, pauseNzb, ncategory, npriority ? atoi(npriority) : 0, nfeedscript); } } else @@ -1452,34 +1452,34 @@ void Options::InitScheduler() char optname[128]; sprintf(optname, "Task%i.Time", n); - const char* szTime = GetOption(optname); + const char* time = GetOption(optname); sprintf(optname, "Task%i.WeekDays", n); - const char* szWeekDays = GetOption(optname); + const char* weekDays = GetOption(optname); sprintf(optname, "Task%i.Command", n); - const char* szCommand = GetOption(optname); + const char* command = GetOption(optname); sprintf(optname, "Task%i.DownloadRate", n); - const char* szDownloadRate = GetOption(optname); + const char* downloadRate = GetOption(optname); sprintf(optname, "Task%i.Process", n); - const char* szProcess = GetOption(optname); + const char* process = GetOption(optname); sprintf(optname, "Task%i.Param", n); - const char* szParam = GetOption(optname); + const char* param = GetOption(optname); - if (Util::EmptyStr(szParam) && !Util::EmptyStr(szProcess)) + if (Util::EmptyStr(param) && !Util::EmptyStr(process)) { - szParam = szProcess; + param = process; } - if (Util::EmptyStr(szParam) && !Util::EmptyStr(szDownloadRate)) + if (Util::EmptyStr(param) && !Util::EmptyStr(downloadRate)) { - szParam = szDownloadRate; + param = downloadRate; } - bool definition = szTime || szWeekDays || szCommand || szDownloadRate || szParam; - bool completed = szTime && szCommand; + bool definition = time || weekDays || command || downloadRate || param; + bool completed = time && command; if (!definition) { @@ -1508,31 +1508,31 @@ void Options::InitScheduler() scActivateServer, scActivateServer, scDeactivateServer, scDeactivateServer, scFetchFeed, scFetchFeed }; const int CommandCount = 27; - ESchedulerCommand eCommand = (ESchedulerCommand)ParseEnumValue(optname, CommandCount, CommandNames, CommandValues); + ESchedulerCommand taskCommand = (ESchedulerCommand)ParseEnumValue(optname, CommandCount, CommandNames, CommandValues); - if (szParam && strlen(szParam) > 0 && eCommand == scProcess && - !Util::SplitCommandLine(szParam, NULL)) + if (param && strlen(param) > 0 && taskCommand == scProcess && + !Util::SplitCommandLine(param, NULL)) { ConfigError("Invalid value for option \"Task%i.Param\"", n); continue; } - int iWeekDays = 0; - if (szWeekDays && !ParseWeekDays(szWeekDays, &iWeekDays)) + int weekDaysVal = 0; + if (weekDays && !ParseWeekDays(weekDays, &weekDaysVal)) { - ConfigError("Invalid value for option \"Task%i.WeekDays\": \"%s\"", n, szWeekDays); + ConfigError("Invalid value for option \"Task%i.WeekDays\": \"%s\"", n, weekDays); continue; } - if (eCommand == scDownloadRate) + if (taskCommand == scDownloadRate) { - if (szParam) + if (param) { - char* szErr; - int iDownloadRate = strtol(szParam, &szErr, 10); - if (!szErr || *szErr != '\0' || iDownloadRate < 0) + char* err; + int downloadRateVal = strtol(param, &err, 10); + if (!err || *err != '\0' || downloadRateVal < 0) { - ConfigError("Invalid value for option \"Task%i.Param\": \"%s\"", n, szDownloadRate); + ConfigError("Invalid value for option \"Task%i.Param\": \"%s\"", n, downloadRate); continue; } } @@ -1543,49 +1543,49 @@ void Options::InitScheduler() } } - if ((eCommand == scScript || - eCommand == scProcess || - eCommand == scActivateServer || - eCommand == scDeactivateServer || - eCommand == scFetchFeed) && - Util::EmptyStr(szParam)) + if ((taskCommand == scScript || + taskCommand == scProcess || + taskCommand == scActivateServer || + taskCommand == scDeactivateServer || + taskCommand == scFetchFeed) && + Util::EmptyStr(param)) { ConfigError("Task definition not complete for \"Task%i\". Option \"Task%i.Param\" is missing", n, n); continue; } - int iHours, iMinutes; - Tokenizer tok(szTime, ";,"); - while (const char* szOneTime = tok.Next()) + int hours, minutes; + Tokenizer tok(time, ";,"); + while (const char* oneTime = tok.Next()) { - if (!ParseTime(szOneTime, &iHours, &iMinutes)) + if (!ParseTime(oneTime, &hours, &minutes)) { - ConfigError("Invalid value for option \"Task%i.Time\": \"%s\"", n, szOneTime); + ConfigError("Invalid value for option \"Task%i.Time\": \"%s\"", n, oneTime); break; } - if (m_pExtender) + if (m_extender) { - if (iHours == -1) + if (hours == -1) { - for (int iEveryHour = 0; iEveryHour < 24; iEveryHour++) + for (int everyHour = 0; everyHour < 24; everyHour++) { - m_pExtender->AddTask(n, iEveryHour, iMinutes, iWeekDays, eCommand, szParam); + m_extender->AddTask(n, everyHour, minutes, weekDaysVal, taskCommand, param); } } else { - m_pExtender->AddTask(n, iHours, iMinutes, iWeekDays, eCommand, szParam); + m_extender->AddTask(n, hours, minutes, weekDaysVal, taskCommand, param); } } } } } -bool Options::ParseTime(const char* szTime, int* pHours, int* pMinutes) +bool Options::ParseTime(const char* time, int* hours, int* minutes) { - int iColons = 0; - const char* p = szTime; + int colons = 0; + const char* p = time; while (*p) { if (!strchr("0123456789: *", *p)) @@ -1594,41 +1594,41 @@ bool Options::ParseTime(const char* szTime, int* pHours, int* pMinutes) } if (*p == ':') { - iColons++; + colons++; } p++; } - if (iColons != 1) + if (colons != 1) { return false; } - const char* szColon = strchr(szTime, ':'); - if (!szColon) + const char* colon = strchr(time, ':'); + if (!colon) { return false; } - if (szTime[0] == '*') + if (time[0] == '*') { - *pHours = -1; + *hours = -1; } else { - *pHours = atoi(szTime); - if (*pHours < 0 || *pHours > 23) + *hours = atoi(time); + if (*hours < 0 || *hours > 23) { return false; } } - if (szColon[1] == '*') + if (colon[1] == '*') { return false; } - *pMinutes = atoi(szColon + 1); - if (*pMinutes < 0 || *pMinutes > 59) + *minutes = atoi(colon + 1); + if (*minutes < 0 || *minutes > 59) { return false; } @@ -1636,43 +1636,43 @@ bool Options::ParseTime(const char* szTime, int* pHours, int* pMinutes) return true; } -bool Options::ParseWeekDays(const char* szWeekDays, int* pWeekDaysBits) +bool Options::ParseWeekDays(const char* weekDays, int* weekDaysBits) { - *pWeekDaysBits = 0; - const char* p = szWeekDays; - int iFirstDay = 0; - bool bRange = false; + *weekDaysBits = 0; + const char* p = weekDays; + int firstDay = 0; + bool range = false; while (*p) { if (strchr("1234567", *p)) { - int iDay = *p - '0'; - if (bRange) + int day = *p - '0'; + if (range) { - if (iDay <= iFirstDay || iFirstDay == 0) + if (day <= firstDay || firstDay == 0) { return false; } - for (int i = iFirstDay; i <= iDay; i++) + for (int i = firstDay; i <= day; i++) { - *pWeekDaysBits |= 1 << (i - 1); + *weekDaysBits |= 1 << (i - 1); } - iFirstDay = 0; + firstDay = 0; } else { - *pWeekDaysBits |= 1 << (iDay - 1); - iFirstDay = iDay; + *weekDaysBits |= 1 << (day - 1); + firstDay = day; } - bRange = false; + range = false; } else if (*p == ',') { - bRange = false; + range = false; } else if (*p == '-') { - bRange = true; + range = true; } else if (*p == ' ') { @@ -1689,25 +1689,25 @@ bool Options::ParseWeekDays(const char* szWeekDays, int* pWeekDaysBits) void Options::LoadConfigFile() { - SetOption(OPTION_CONFIGFILE, m_szConfigFilename); + SetOption(OPTION_CONFIGFILE, m_configFilename); - FILE* infile = fopen(m_szConfigFilename, FOPEN_RB); + FILE* infile = fopen(m_configFilename, FOPEN_RB); if (!infile) { - ConfigError("Could not open file %s", m_szConfigFilename); - m_bFatalError = true; + ConfigError("Could not open file %s", m_configFilename); + m_fatalError = true; return; } - m_iConfigLine = 0; - int iBufLen = (int)Util::FileSize(m_szConfigFilename) + 1; - char* buf = (char*)malloc(iBufLen); + m_configLine = 0; + int bufLen = (int)Util::FileSize(m_configFilename) + 1; + char* buf = (char*)malloc(bufLen); - int iLine = 0; - while (fgets(buf, iBufLen - 1, infile)) + int line = 0; + while (fgets(buf, bufLen - 1, infile)) { - m_iConfigLine = ++iLine; + m_configLine = ++line; if (buf[0] != 0 && buf[strlen(buf)-1] == '\n') { @@ -1729,12 +1729,12 @@ void Options::LoadConfigFile() fclose(infile); free(buf); - m_iConfigLine = 0; + m_configLine = 0; } -void Options::InitCommandLineOptions(CmdOptList* pCommandLineOptions) +void Options::InitCommandLineOptions(CmdOptList* commandLineOptions) { - for (CmdOptList::iterator it = pCommandLineOptions->begin(); it != pCommandLineOptions->end(); it++) + for (CmdOptList::iterator it = commandLineOptions->begin(); it != commandLineOptions->end(); it++) { const char* option = *it; SetOptionString(option); @@ -1752,8 +1752,8 @@ bool Options::SetOptionString(const char* option) return false; } - bool bOK = ValidateOptionName(optname, optvalue); - if (bOK) + bool ok = ValidateOptionName(optname, optvalue); + if (ok) { SetOption(optname, optvalue); } @@ -1765,7 +1765,7 @@ bool Options::SetOptionString(const char* option) free(optname); free(optvalue); - return bOK; + return ok; } /* @@ -1775,7 +1775,7 @@ bool Options::SetOptionString(const char* option) * Returns true if the option string has name and value; * If "true" is returned the caller is responsible for freeing optname and optvalue. */ -bool Options::SplitOptionString(const char* option, char** pOptName, char** pOptValue) +bool Options::SplitOptionString(const char* option, char** optName, char** optValue) { const char* eq = strchr(option, '='); if (!eq) @@ -1806,8 +1806,8 @@ bool Options::SplitOptionString(const char* option, char** pOptName, char** pOpt value = optvalue; } - *pOptName = strdup(optname); - *pOptValue = strdup(value); + *optName = strdup(optname); + *optValue = strdup(value); return true; } @@ -1928,93 +1928,93 @@ bool Options::ValidateOptionName(const char* optname, const char* optvalue) return false; } -void Options::ConvertOldOption(char *szOption, int iOptionBufLen, char *szValue, int iValueBufLen) +void Options::ConvertOldOption(char *option, int optionBufLen, char *value, int valueBufLen) { // for compatibility with older versions accept old option names - if (!strcasecmp(szOption, "$MAINDIR")) + if (!strcasecmp(option, "$MAINDIR")) { - strncpy(szOption, "MainDir", iOptionBufLen); + strncpy(option, "MainDir", optionBufLen); } - if (!strcasecmp(szOption, "ServerIP")) + if (!strcasecmp(option, "ServerIP")) { - strncpy(szOption, "ControlIP", iOptionBufLen); + strncpy(option, "ControlIP", optionBufLen); } - if (!strcasecmp(szOption, "ServerPort")) + if (!strcasecmp(option, "ServerPort")) { - strncpy(szOption, "ControlPort", iOptionBufLen); + strncpy(option, "ControlPort", optionBufLen); } - if (!strcasecmp(szOption, "ServerPassword")) + if (!strcasecmp(option, "ServerPassword")) { - strncpy(szOption, "ControlPassword", iOptionBufLen); + strncpy(option, "ControlPassword", optionBufLen); } - if (!strcasecmp(szOption, "PostPauseQueue")) + if (!strcasecmp(option, "PostPauseQueue")) { - strncpy(szOption, "ScriptPauseQueue", iOptionBufLen); + strncpy(option, "ScriptPauseQueue", optionBufLen); } - if (!strcasecmp(szOption, "ParCheck") && !strcasecmp(szValue, "yes")) + if (!strcasecmp(option, "ParCheck") && !strcasecmp(value, "yes")) { - strncpy(szValue, "always", iValueBufLen); + strncpy(value, "always", valueBufLen); } - if (!strcasecmp(szOption, "ParCheck") && !strcasecmp(szValue, "no")) + if (!strcasecmp(option, "ParCheck") && !strcasecmp(value, "no")) { - strncpy(szValue, "auto", iValueBufLen); + strncpy(value, "auto", valueBufLen); } - if (!strcasecmp(szOption, "ParScan") && !strcasecmp(szValue, "auto")) + if (!strcasecmp(option, "ParScan") && !strcasecmp(value, "auto")) { - strncpy(szValue, "extended", iValueBufLen); + strncpy(value, "extended", valueBufLen); } - if (!strcasecmp(szOption, "DefScript")) + if (!strcasecmp(option, "DefScript")) { - strncpy(szOption, "PostScript", iOptionBufLen); + strncpy(option, "PostScript", optionBufLen); } - int iNameLen = strlen(szOption); - if (!strncasecmp(szOption, "Category", 8) && iNameLen > 10 && - !strcasecmp(szOption + iNameLen - 10, ".DefScript")) + int nameLen = strlen(option); + if (!strncasecmp(option, "Category", 8) && nameLen > 10 && + !strcasecmp(option + nameLen - 10, ".DefScript")) { - strncpy(szOption + iNameLen - 10, ".PostScript", iOptionBufLen - 9 /* strlen("Category.") */); + strncpy(option + nameLen - 10, ".PostScript", optionBufLen - 9 /* strlen("Category.") */); } - if (!strcasecmp(szOption, "WriteBufferSize")) + if (!strcasecmp(option, "WriteBufferSize")) { - strncpy(szOption, "WriteBuffer", iOptionBufLen); - int val = strtol(szValue, NULL, 10); + strncpy(option, "WriteBuffer", optionBufLen); + int val = strtol(value, NULL, 10); val = val == -1 ? 1024 : val / 1024; - snprintf(szValue, iValueBufLen, "%i", val); + snprintf(value, valueBufLen, "%i", val); } - if (!strcasecmp(szOption, "ConnectionTimeout")) + if (!strcasecmp(option, "ConnectionTimeout")) { - strncpy(szOption, "ArticleTimeout", iOptionBufLen); + strncpy(option, "ArticleTimeout", optionBufLen); } - if (!strcasecmp(szOption, "CreateBrokenLog")) + if (!strcasecmp(option, "CreateBrokenLog")) { - strncpy(szOption, "BrokenLog", iOptionBufLen); + strncpy(option, "BrokenLog", optionBufLen); } - szOption[iOptionBufLen-1] = '\0'; - szOption[iValueBufLen-1] = '\0'; + option[optionBufLen-1] = '\0'; + option[valueBufLen-1] = '\0'; } void Options::CheckOptions() { #ifdef DISABLE_PARCHECK - if (m_eParCheck != pcManual) + if (m_parCheck != pcManual) { LocateOptionSrcPos(OPTION_PARCHECK); ConfigError("Invalid value for option \"%s\": program was compiled without parcheck-support", OPTION_PARCHECK); } - if (m_bParRename) + if (m_parRename) { LocateOptionSrcPos(OPTION_PARRENAME); ConfigError("Invalid value for option \"%s\": program was compiled without parcheck-support", OPTION_PARRENAME); @@ -2022,7 +2022,7 @@ void Options::CheckOptions() #endif #ifdef DISABLE_CURSES - if (m_eOutputMode == omNCurses) + if (m_outputMode == omNCurses) { LocateOptionSrcPos(OPTION_OUTPUTMODE); ConfigError("Invalid value for option \"%s\": program was compiled without curses-support", OPTION_OUTPUTMODE); @@ -2030,69 +2030,69 @@ void Options::CheckOptions() #endif #ifdef DISABLE_TLS - if (m_bSecureControl) + if (m_secureControl) { LocateOptionSrcPos(OPTION_SECURECONTROL); ConfigError("Invalid value for option \"%s\": program was compiled without TLS/SSL-support", OPTION_SECURECONTROL); } #endif - if (!m_bDecode) + if (!m_decode) { - m_bDirectWrite = false; + m_directWrite = false; } // if option "ConfigTemplate" is not set, use "WebDir" as default location for template // (for compatibility with versions 9 and 10). - if (Util::EmptyStr(m_szConfigTemplate) && !m_bNoDiskAccess) + if (Util::EmptyStr(m_configTemplate) && !m_noDiskAccess) { - free(m_szConfigTemplate); - int iLen = strlen(m_szWebDir) + 15; - m_szConfigTemplate = (char*)malloc(iLen); - snprintf(m_szConfigTemplate, iLen, "%s%s", m_szWebDir, "nzbget.conf"); - m_szConfigTemplate[iLen-1] = '\0'; - if (!Util::FileExists(m_szConfigTemplate)) + free(m_configTemplate); + int len = strlen(m_webDir) + 15; + m_configTemplate = (char*)malloc(len); + snprintf(m_configTemplate, len, "%s%s", m_webDir, "nzbget.conf"); + m_configTemplate[len-1] = '\0'; + if (!Util::FileExists(m_configTemplate)) { - free(m_szConfigTemplate); - m_szConfigTemplate = strdup(""); + free(m_configTemplate); + m_configTemplate = strdup(""); } } - if (m_iArticleCache < 0) + if (m_articleCache < 0) { - m_iArticleCache = 0; + m_articleCache = 0; } - else if (sizeof(void*) == 4 && m_iArticleCache > 1900) + else if (sizeof(void*) == 4 && m_articleCache > 1900) { - ConfigError("Invalid value for option \"ArticleCache\": %i. Changed to 1900", m_iArticleCache); - m_iArticleCache = 1900; + ConfigError("Invalid value for option \"ArticleCache\": %i. Changed to 1900", m_articleCache); + m_articleCache = 1900; } - else if (sizeof(void*) == 4 && m_iParBuffer > 1900) + else if (sizeof(void*) == 4 && m_parBuffer > 1900) { - ConfigError("Invalid value for option \"ParBuffer\": %i. Changed to 1900", m_iParBuffer); - m_iParBuffer = 1900; + ConfigError("Invalid value for option \"ParBuffer\": %i. Changed to 1900", m_parBuffer); + m_parBuffer = 1900; } - if (sizeof(void*) == 4 && m_iParBuffer + m_iArticleCache > 1900) + if (sizeof(void*) == 4 && m_parBuffer + m_articleCache > 1900) { ConfigError("Options \"ArticleCache\" and \"ParBuffer\" in total cannot use more than 1900MB of memory in 32-Bit mode. Changed to 1500 and 400"); - m_iArticleCache = 1900; - m_iParBuffer = 400; + m_articleCache = 1900; + m_parBuffer = 400; } - if (!Util::EmptyStr(m_szUnpackPassFile) && !Util::FileExists(m_szUnpackPassFile)) + if (!Util::EmptyStr(m_unpackPassFile) && !Util::FileExists(m_unpackPassFile)) { - ConfigError("Invalid value for option \"UnpackPassFile\": %s. File not found", m_szUnpackPassFile); + ConfigError("Invalid value for option \"UnpackPassFile\": %s. File not found", m_unpackPassFile); } } Options::OptEntries* Options::LockOptEntries() { - m_mutexOptEntries.Lock(); - return &m_OptEntries; + m_optEntriesMutex.Lock(); + return &m_optEntries; } void Options::UnlockOptEntries() { - m_mutexOptEntries.Unlock(); + m_optEntriesMutex.Unlock(); } diff --git a/daemon/main/Options.h b/daemon/main/Options.h index 245bb177..bc1489c8 100644 --- a/daemon/main/Options.h +++ b/daemon/main/Options.h @@ -96,25 +96,25 @@ public: class OptEntry { private: - char* m_szName; - char* m_szValue; - char* m_szDefValue; - int m_iLineNo; + char* m_name; + char* m_value; + char* m_defValue; + int m_lineNo; - void SetLineNo(int iLineNo) { m_iLineNo = iLineNo; } + void SetLineNo(int lineNo) { m_lineNo = lineNo; } friend class Options; public: OptEntry(); - OptEntry(const char* szName, const char* szValue); + OptEntry(const char* name, const char* value); ~OptEntry(); - void SetName(const char* szName); - const char* GetName() { return m_szName; } - void SetValue(const char* szValue); - const char* GetValue() { return m_szValue; } - const char* GetDefValue() { return m_szDefValue; } - int GetLineNo() { return m_iLineNo; } + void SetName(const char* name); + const char* GetName() { return m_name; } + void SetValue(const char* value); + const char* GetValue() { return m_value; } + const char* GetDefValue() { return m_defValue; } + int GetLineNo() { return m_lineNo; } bool Restricted(); }; @@ -124,7 +124,7 @@ public: { public: ~OptEntries(); - OptEntry* FindOption(const char* szName); + OptEntry* FindOption(const char* name); }; typedef std::vector NameList; @@ -133,20 +133,20 @@ public: class Category { private: - char* m_szName; - char* m_szDestDir; - bool m_bUnpack; - char* m_szPostScript; - NameList m_Aliases; + char* m_name; + char* m_destDir; + bool m_unpack; + char* m_postScript; + NameList m_aliases; public: - Category(const char* szName, const char* szDestDir, bool bUnpack, const char* szPostScript); + Category(const char* name, const char* destDir, bool unpack, const char* postScript); ~Category(); - const char* GetName() { return m_szName; } - const char* GetDestDir() { return m_szDestDir; } - bool GetUnpack() { return m_bUnpack; } - const char* GetPostScript() { return m_szPostScript; } - NameList* GetAliases() { return &m_Aliases; } + const char* GetName() { return m_name; } + const char* GetDestDir() { return m_destDir; } + bool GetUnpack() { return m_unpack; } + const char* GetPostScript() { return m_postScript; } + NameList* GetAliases() { return &m_aliases; } }; typedef std::vector CategoriesBase; @@ -155,150 +155,150 @@ public: { public: ~Categories(); - Category* FindCategory(const char* szName, bool bSearchAliases); + Category* FindCategory(const char* name, bool searchAliases); }; class Extender { public: - virtual void AddNewsServer(int iID, bool bActive, const char* szName, const char* szHost, - int iPort, const char* szUser, const char* szPass, bool bJoinGroup, - bool bTLS, const char* szCipher, int iMaxConnections, int iRetention, - int iLevel, int iGroup) = 0; - virtual void AddFeed(int iID, const char* szName, const char* szUrl, int iInterval, - const char* szFilter, bool bBacklog, bool bPauseNzb, const char* szCategory, - int iPriority, const char* szFeedScript) {} - virtual void AddTask(int iID, int iHours, int iMinutes, int iWeekDaysBits, ESchedulerCommand eCommand, - const char* szParam) {} + virtual void AddNewsServer(int id, bool active, const char* name, const char* host, + int port, const char* user, const char* pass, bool joinGroup, + bool tLS, const char* cipher, int maxConnections, int retention, + int level, int group) = 0; + virtual void AddFeed(int id, const char* name, const char* url, int interval, + const char* filter, bool backlog, bool pauseNzb, const char* category, + int priority, const char* feedScript) {} + virtual void AddTask(int id, int hours, int minutes, int weekDaysBits, ESchedulerCommand command, + const char* param) {} virtual void SetupFirstStart() {} }; private: - OptEntries m_OptEntries; - Mutex m_mutexOptEntries; - Categories m_Categories; - bool m_bNoDiskAccess; - bool m_bFatalError; - Extender* m_pExtender; + OptEntries m_optEntries; + Mutex m_optEntriesMutex; + Categories m_categories; + bool m_noDiskAccess; + bool m_fatalError; + Extender* m_extender; // Options - bool m_bConfigErrors; - int m_iConfigLine; - char* m_szAppDir; - char* m_szConfigFilename; - char* m_szDestDir; - char* m_szInterDir; - char* m_szTempDir; - char* m_szQueueDir; - char* m_szNzbDir; - char* m_szWebDir; - char* m_szConfigTemplate; - char* m_szScriptDir; - char* m_szRequiredDir; - EMessageTarget m_eInfoTarget; - EMessageTarget m_eWarningTarget; - EMessageTarget m_eErrorTarget; - EMessageTarget m_eDebugTarget; - EMessageTarget m_eDetailTarget; - bool m_bDecode; - bool m_bBrokenLog; - bool m_bNzbLog; - int m_iArticleTimeout; - int m_iUrlTimeout; - int m_iTerminateTimeout; - bool m_bAppendCategoryDir; - bool m_bContinuePartial; - int m_iRetries; - int m_iRetryInterval; - bool m_bSaveQueue; - bool m_bFlushQueue; - bool m_bDupeCheck; - char* m_szControlIP; - char* m_szControlUsername; - char* m_szControlPassword; - char* m_szRestrictedUsername; - char* m_szRestrictedPassword; - char* m_szAddUsername; - char* m_szAddPassword; - int m_iControlPort; - bool m_bSecureControl; - int m_iSecurePort; - char* m_szSecureCert; - char* m_szSecureKey; - char* m_szAuthorizedIP; - char* m_szLockFile; - char* m_szDaemonUsername; - EOutputMode m_eOutputMode; - bool m_bReloadQueue; - int m_iUrlConnections; - int m_iLogBufferSize; - EWriteLog m_eWriteLog; - int m_iRotateLog; - char* m_szLogFile; - EParCheck m_eParCheck; - bool m_bParRepair; - EParScan m_eParScan; - bool m_bParQuick; - bool m_bParRename; - int m_iParBuffer; - int m_iParThreads; - EHealthCheck m_eHealthCheck; - char* m_szPostScript; - char* m_szScriptOrder; - char* m_szScanScript; - char* m_szQueueScript; - char* m_szFeedScript; - bool m_bNoConfig; - int m_iUMask; - int m_iUpdateInterval; - bool m_bCursesNZBName; - bool m_bCursesTime; - bool m_bCursesGroup; - bool m_bCrcCheck; - bool m_bDirectWrite; - int m_iWriteBuffer; - int m_iNzbDirInterval; - int m_iNzbDirFileAge; - bool m_bParCleanupQueue; - int m_iDiskSpace; - bool m_bTLS; - bool m_bDumpCore; - bool m_bParPauseQueue; - bool m_bScriptPauseQueue; - bool m_bNzbCleanupDisk; - bool m_bDeleteCleanupDisk; - int m_iParTimeLimit; - int m_iKeepHistory; - bool m_bAccurateRate; - bool m_bUnpack; - bool m_bUnpackCleanupDisk; - char* m_szUnrarCmd; - char* m_szSevenZipCmd; - char* m_szUnpackPassFile; - bool m_bUnpackPauseQueue; - char* m_szExtCleanupDisk; - char* m_szParIgnoreExt; - int m_iFeedHistory; - bool m_bUrlForce; - int m_iTimeCorrection; - int m_iPropagationDelay; - int m_iArticleCache; - int m_iEventInterval; + bool m_configErrors; + int m_configLine; + char* m_appDir; + char* m_configFilename; + char* m_destDir; + char* m_interDir; + char* m_tempDir; + char* m_queueDir; + char* m_nzbDir; + char* m_webDir; + char* m_configTemplate; + char* m_scriptDir; + char* m_requiredDir; + EMessageTarget m_infoTarget; + EMessageTarget m_warningTarget; + EMessageTarget m_errorTarget; + EMessageTarget m_debugTarget; + EMessageTarget m_detailTarget; + bool m_decode; + bool m_brokenLog; + bool m_nzbLog; + int m_articleTimeout; + int m_urlTimeout; + int m_terminateTimeout; + bool m_appendCategoryDir; + bool m_continuePartial; + int m_retries; + int m_retryInterval; + bool m_saveQueue; + bool m_flushQueue; + bool m_dupeCheck; + char* m_controlIP; + char* m_controlUsername; + char* m_controlPassword; + char* m_restrictedUsername; + char* m_restrictedPassword; + char* m_addUsername; + char* m_addPassword; + int m_controlPort; + bool m_secureControl; + int m_securePort; + char* m_secureCert; + char* m_secureKey; + char* m_authorizedIP; + char* m_lockFile; + char* m_daemonUsername; + EOutputMode m_outputMode; + bool m_reloadQueue; + int m_urlConnections; + int m_logBufferSize; + EWriteLog m_writeLog; + int m_rotateLog; + char* m_logFile; + EParCheck m_parCheck; + bool m_parRepair; + EParScan m_parScan; + bool m_parQuick; + bool m_parRename; + int m_parBuffer; + int m_parThreads; + EHealthCheck m_healthCheck; + char* m_postScript; + char* m_scriptOrder; + char* m_scanScript; + char* m_queueScript; + char* m_feedScript; + bool m_noConfig; + int m_uMask; + int m_updateInterval; + bool m_cursesNzbName; + bool m_cursesTime; + bool m_cursesGroup; + bool m_crcCheck; + bool m_directWrite; + int m_writeBuffer; + int m_nzbDirInterval; + int m_nzbDirFileAge; + bool m_parCleanupQueue; + int m_diskSpace; + bool m_tLS; + bool m_dumpCore; + bool m_parPauseQueue; + bool m_scriptPauseQueue; + bool m_nzbCleanupDisk; + bool m_deleteCleanupDisk; + int m_parTimeLimit; + int m_keepHistory; + bool m_accurateRate; + bool m_unpack; + bool m_unpackCleanupDisk; + char* m_unrarCmd; + char* m_sevenZipCmd; + char* m_unpackPassFile; + bool m_unpackPauseQueue; + char* m_extCleanupDisk; + char* m_parIgnoreExt; + int m_feedHistory; + bool m_urlForce; + int m_timeCorrection; + int m_propagationDelay; + int m_articleCache; + int m_eventInterval; // Current state - bool m_bServerMode; - bool m_bRemoteClientMode; - bool m_bPauseDownload; - bool m_bPausePostProcess; - bool m_bPauseScan; - bool m_bTempPauseDownload; - int m_iDownloadRate; - time_t m_tResumeTime; - int m_iLocalTimeOffset; - bool m_bTempPausePostprocess; + bool m_serverMode; + bool m_remoteClientMode; + bool m_pauseDownload; + bool m_pausePostProcess; + bool m_pauseScan; + bool m_tempPauseDownload; + int m_downloadRate; + time_t m_resumeTime; + int m_localTimeOffset; + bool m_tempPausePostprocess; - void Init(const char* szExeName, const char* szConfigFilename, bool bNoConfig, - CmdOptList* pCommandLineOptions, bool bNoDiskAccess, Extender* pExtender); + void Init(const char* exeName, const char* configFilename, bool noConfig, + CmdOptList* commandLineOptions, bool noDiskAccess, Extender* extender); void InitDefaults(); void InitOptions(); void InitOptFile(); @@ -306,163 +306,163 @@ private: void InitCategories(); void InitScheduler(); void InitFeeds(); - void InitCommandLineOptions(CmdOptList* pCommandLineOptions); + void InitCommandLineOptions(CmdOptList* commandLineOptions); void CheckOptions(); void Dump(); int ParseEnumValue(const char* OptName, int argc, const char* argn[], const int argv[]); - int ParseIntValue(const char* OptName, int iBase); + int ParseIntValue(const char* OptName, int base); OptEntry* FindOption(const char* optname); const char* GetOption(const char* optname); void SetOption(const char* optname, const char* value); bool SetOptionString(const char* option); bool ValidateOptionName(const char* optname, const char* optvalue); void LoadConfigFile(); - void CheckDir(char** dir, const char* szOptionName, const char* szParentDir, - bool bAllowEmpty, bool bCreate); - bool ParseTime(const char* szTime, int* pHours, int* pMinutes); - bool ParseWeekDays(const char* szWeekDays, int* pWeekDaysBits); + void CheckDir(char** dir, const char* optionName, const char* parentDir, + bool allowEmpty, bool create); + bool ParseTime(const char* time, int* hours, int* minutes); + bool ParseWeekDays(const char* weekDays, int* weekDaysBits); void ConfigError(const char* msg, ...); void ConfigWarn(const char* msg, ...); - void LocateOptionSrcPos(const char *szOptionName); - void ConvertOldOption(char *szOption, int iOptionBufLen, char *szValue, int iValueBufLen); + void LocateOptionSrcPos(const char *optionName); + void ConvertOldOption(char *option, int optionBufLen, char *value, int valueBufLen); public: - Options(const char* szExeName, const char* szConfigFilename, bool bNoConfig, - CmdOptList* pCommandLineOptions, Extender* pExtender); - Options(CmdOptList* pCommandLineOptions, Extender* pExtender); + Options(const char* exeName, const char* configFilename, bool noConfig, + CmdOptList* commandLineOptions, Extender* extender); + Options(CmdOptList* commandLineOptions, Extender* extender); ~Options(); - bool SplitOptionString(const char* option, char** pOptName, char** pOptValue); - bool GetFatalError() { return m_bFatalError; } + bool SplitOptionString(const char* option, char** optName, char** optValue); + bool GetFatalError() { return m_fatalError; } OptEntries* LockOptEntries(); void UnlockOptEntries(); // Options - const char* GetConfigFilename() { return m_szConfigFilename; } - bool GetConfigErrors() { return m_bConfigErrors; } - const char* GetAppDir() { return m_szAppDir; } - const char* GetDestDir() { return m_szDestDir; } - const char* GetInterDir() { return m_szInterDir; } - const char* GetTempDir() { return m_szTempDir; } - const char* GetQueueDir() { return m_szQueueDir; } - const char* GetNzbDir() { return m_szNzbDir; } - const char* GetWebDir() { return m_szWebDir; } - const char* GetConfigTemplate() { return m_szConfigTemplate; } - const char* GetScriptDir() { return m_szScriptDir; } - const char* GetRequiredDir() { return m_szRequiredDir; } - bool GetBrokenLog() const { return m_bBrokenLog; } - bool GetNzbLog() const { return m_bNzbLog; } - EMessageTarget GetInfoTarget() const { return m_eInfoTarget; } - EMessageTarget GetWarningTarget() const { return m_eWarningTarget; } - EMessageTarget GetErrorTarget() const { return m_eErrorTarget; } - EMessageTarget GetDebugTarget() const { return m_eDebugTarget; } - EMessageTarget GetDetailTarget() const { return m_eDetailTarget; } - int GetArticleTimeout() { return m_iArticleTimeout; } - int GetUrlTimeout() { return m_iUrlTimeout; } - int GetTerminateTimeout() { return m_iTerminateTimeout; } - bool GetDecode() { return m_bDecode; }; - bool GetAppendCategoryDir() { return m_bAppendCategoryDir; } - bool GetContinuePartial() { return m_bContinuePartial; } - int GetRetries() { return m_iRetries; } - int GetRetryInterval() { return m_iRetryInterval; } - bool GetSaveQueue() { return m_bSaveQueue; } - bool GetFlushQueue() { return m_bFlushQueue; } - bool GetDupeCheck() { return m_bDupeCheck; } - const char* GetControlIP() { return m_szControlIP; } - const char* GetControlUsername() { return m_szControlUsername; } - const char* GetControlPassword() { return m_szControlPassword; } - const char* GetRestrictedUsername() { return m_szRestrictedUsername; } - const char* GetRestrictedPassword() { return m_szRestrictedPassword; } - const char* GetAddUsername() { return m_szAddUsername; } - const char* GetAddPassword() { return m_szAddPassword; } - int GetControlPort() { return m_iControlPort; } - bool GetSecureControl() { return m_bSecureControl; } - int GetSecurePort() { return m_iSecurePort; } - const char* GetSecureCert() { return m_szSecureCert; } - const char* GetSecureKey() { return m_szSecureKey; } - const char* GetAuthorizedIP() { return m_szAuthorizedIP; } - const char* GetLockFile() { return m_szLockFile; } - const char* GetDaemonUsername() { return m_szDaemonUsername; } - EOutputMode GetOutputMode() { return m_eOutputMode; } - bool GetReloadQueue() { return m_bReloadQueue; } - int GetUrlConnections() { return m_iUrlConnections; } - int GetLogBufferSize() { return m_iLogBufferSize; } - EWriteLog GetWriteLog() { return m_eWriteLog; } - const char* GetLogFile() { return m_szLogFile; } - int GetRotateLog() { return m_iRotateLog; } - EParCheck GetParCheck() { return m_eParCheck; } - bool GetParRepair() { return m_bParRepair; } - EParScan GetParScan() { return m_eParScan; } - bool GetParQuick() { return m_bParQuick; } - bool GetParRename() { return m_bParRename; } - int GetParBuffer() { return m_iParBuffer; } - int GetParThreads() { return m_iParThreads; } - EHealthCheck GetHealthCheck() { return m_eHealthCheck; } - const char* GetScriptOrder() { return m_szScriptOrder; } - const char* GetPostScript() { return m_szPostScript; } - const char* GetScanScript() { return m_szScanScript; } - const char* GetQueueScript() { return m_szQueueScript; } - const char* GetFeedScript() { return m_szFeedScript; } - int GetUMask() { return m_iUMask; } - int GetUpdateInterval() {return m_iUpdateInterval; } - bool GetCursesNZBName() { return m_bCursesNZBName; } - bool GetCursesTime() { return m_bCursesTime; } - bool GetCursesGroup() { return m_bCursesGroup; } - bool GetCrcCheck() { return m_bCrcCheck; } - bool GetDirectWrite() { return m_bDirectWrite; } - int GetWriteBuffer() { return m_iWriteBuffer; } - int GetNzbDirInterval() { return m_iNzbDirInterval; } - int GetNzbDirFileAge() { return m_iNzbDirFileAge; } - bool GetParCleanupQueue() { return m_bParCleanupQueue; } - int GetDiskSpace() { return m_iDiskSpace; } - bool GetTLS() { return m_bTLS; } - bool GetDumpCore() { return m_bDumpCore; } - bool GetParPauseQueue() { return m_bParPauseQueue; } - bool GetScriptPauseQueue() { return m_bScriptPauseQueue; } - bool GetNzbCleanupDisk() { return m_bNzbCleanupDisk; } - bool GetDeleteCleanupDisk() { return m_bDeleteCleanupDisk; } - int GetParTimeLimit() { return m_iParTimeLimit; } - int GetKeepHistory() { return m_iKeepHistory; } - bool GetAccurateRate() { return m_bAccurateRate; } - bool GetUnpack() { return m_bUnpack; } - bool GetUnpackCleanupDisk() { return m_bUnpackCleanupDisk; } - const char* GetUnrarCmd() { return m_szUnrarCmd; } - const char* GetSevenZipCmd() { return m_szSevenZipCmd; } - const char* GetUnpackPassFile() { return m_szUnpackPassFile; } - bool GetUnpackPauseQueue() { return m_bUnpackPauseQueue; } - const char* GetExtCleanupDisk() { return m_szExtCleanupDisk; } - const char* GetParIgnoreExt() { return m_szParIgnoreExt; } - int GetFeedHistory() { return m_iFeedHistory; } - bool GetUrlForce() { return m_bUrlForce; } - int GetTimeCorrection() { return m_iTimeCorrection; } - int GetPropagationDelay() { return m_iPropagationDelay; } - int GetArticleCache() { return m_iArticleCache; } - int GetEventInterval() { return m_iEventInterval; } + const char* GetConfigFilename() { return m_configFilename; } + bool GetConfigErrors() { return m_configErrors; } + const char* GetAppDir() { return m_appDir; } + const char* GetDestDir() { return m_destDir; } + const char* GetInterDir() { return m_interDir; } + const char* GetTempDir() { return m_tempDir; } + const char* GetQueueDir() { return m_queueDir; } + const char* GetNzbDir() { return m_nzbDir; } + const char* GetWebDir() { return m_webDir; } + const char* GetConfigTemplate() { return m_configTemplate; } + const char* GetScriptDir() { return m_scriptDir; } + const char* GetRequiredDir() { return m_requiredDir; } + bool GetBrokenLog() const { return m_brokenLog; } + bool GetNzbLog() const { return m_nzbLog; } + EMessageTarget GetInfoTarget() const { return m_infoTarget; } + EMessageTarget GetWarningTarget() const { return m_warningTarget; } + EMessageTarget GetErrorTarget() const { return m_errorTarget; } + EMessageTarget GetDebugTarget() const { return m_debugTarget; } + EMessageTarget GetDetailTarget() const { return m_detailTarget; } + int GetArticleTimeout() { return m_articleTimeout; } + int GetUrlTimeout() { return m_urlTimeout; } + int GetTerminateTimeout() { return m_terminateTimeout; } + bool GetDecode() { return m_decode; }; + bool GetAppendCategoryDir() { return m_appendCategoryDir; } + bool GetContinuePartial() { return m_continuePartial; } + int GetRetries() { return m_retries; } + int GetRetryInterval() { return m_retryInterval; } + bool GetSaveQueue() { return m_saveQueue; } + bool GetFlushQueue() { return m_flushQueue; } + bool GetDupeCheck() { return m_dupeCheck; } + const char* GetControlIP() { return m_controlIP; } + const char* GetControlUsername() { return m_controlUsername; } + const char* GetControlPassword() { return m_controlPassword; } + const char* GetRestrictedUsername() { return m_restrictedUsername; } + const char* GetRestrictedPassword() { return m_restrictedPassword; } + const char* GetAddUsername() { return m_addUsername; } + const char* GetAddPassword() { return m_addPassword; } + int GetControlPort() { return m_controlPort; } + bool GetSecureControl() { return m_secureControl; } + int GetSecurePort() { return m_securePort; } + const char* GetSecureCert() { return m_secureCert; } + const char* GetSecureKey() { return m_secureKey; } + const char* GetAuthorizedIP() { return m_authorizedIP; } + const char* GetLockFile() { return m_lockFile; } + const char* GetDaemonUsername() { return m_daemonUsername; } + EOutputMode GetOutputMode() { return m_outputMode; } + bool GetReloadQueue() { return m_reloadQueue; } + int GetUrlConnections() { return m_urlConnections; } + int GetLogBufferSize() { return m_logBufferSize; } + EWriteLog GetWriteLog() { return m_writeLog; } + const char* GetLogFile() { return m_logFile; } + int GetRotateLog() { return m_rotateLog; } + EParCheck GetParCheck() { return m_parCheck; } + bool GetParRepair() { return m_parRepair; } + EParScan GetParScan() { return m_parScan; } + bool GetParQuick() { return m_parQuick; } + bool GetParRename() { return m_parRename; } + int GetParBuffer() { return m_parBuffer; } + int GetParThreads() { return m_parThreads; } + EHealthCheck GetHealthCheck() { return m_healthCheck; } + const char* GetScriptOrder() { return m_scriptOrder; } + const char* GetPostScript() { return m_postScript; } + const char* GetScanScript() { return m_scanScript; } + const char* GetQueueScript() { return m_queueScript; } + const char* GetFeedScript() { return m_feedScript; } + int GetUMask() { return m_uMask; } + int GetUpdateInterval() {return m_updateInterval; } + bool GetCursesNZBName() { return m_cursesNzbName; } + bool GetCursesTime() { return m_cursesTime; } + bool GetCursesGroup() { return m_cursesGroup; } + bool GetCrcCheck() { return m_crcCheck; } + bool GetDirectWrite() { return m_directWrite; } + int GetWriteBuffer() { return m_writeBuffer; } + int GetNzbDirInterval() { return m_nzbDirInterval; } + int GetNzbDirFileAge() { return m_nzbDirFileAge; } + bool GetParCleanupQueue() { return m_parCleanupQueue; } + int GetDiskSpace() { return m_diskSpace; } + bool GetTLS() { return m_tLS; } + bool GetDumpCore() { return m_dumpCore; } + bool GetParPauseQueue() { return m_parPauseQueue; } + bool GetScriptPauseQueue() { return m_scriptPauseQueue; } + bool GetNzbCleanupDisk() { return m_nzbCleanupDisk; } + bool GetDeleteCleanupDisk() { return m_deleteCleanupDisk; } + int GetParTimeLimit() { return m_parTimeLimit; } + int GetKeepHistory() { return m_keepHistory; } + bool GetAccurateRate() { return m_accurateRate; } + bool GetUnpack() { return m_unpack; } + bool GetUnpackCleanupDisk() { return m_unpackCleanupDisk; } + const char* GetUnrarCmd() { return m_unrarCmd; } + const char* GetSevenZipCmd() { return m_sevenZipCmd; } + const char* GetUnpackPassFile() { return m_unpackPassFile; } + bool GetUnpackPauseQueue() { return m_unpackPauseQueue; } + const char* GetExtCleanupDisk() { return m_extCleanupDisk; } + const char* GetParIgnoreExt() { return m_parIgnoreExt; } + int GetFeedHistory() { return m_feedHistory; } + bool GetUrlForce() { return m_urlForce; } + int GetTimeCorrection() { return m_timeCorrection; } + int GetPropagationDelay() { return m_propagationDelay; } + int GetArticleCache() { return m_articleCache; } + int GetEventInterval() { return m_eventInterval; } - Categories* GetCategories() { return &m_Categories; } - Category* FindCategory(const char* szName, bool bSearchAliases) { return m_Categories.FindCategory(szName, bSearchAliases); } + Categories* GetCategories() { return &m_categories; } + Category* FindCategory(const char* name, bool searchAliases) { return m_categories.FindCategory(name, searchAliases); } // Current state - void SetServerMode(bool bServerMode) { m_bServerMode = bServerMode; } - bool GetServerMode() { return m_bServerMode; } - void SetRemoteClientMode(bool bRemoteClientMode) { m_bRemoteClientMode = bRemoteClientMode; } - bool GetRemoteClientMode() { return m_bRemoteClientMode; } - void SetPauseDownload(bool bPauseDownload) { m_bPauseDownload = bPauseDownload; } - bool GetPauseDownload() const { return m_bPauseDownload; } - void SetPausePostProcess(bool bPausePostProcess) { m_bPausePostProcess = bPausePostProcess; } - bool GetPausePostProcess() const { return m_bPausePostProcess; } - void SetPauseScan(bool bPauseScan) { m_bPauseScan = bPauseScan; } - bool GetPauseScan() const { return m_bPauseScan; } - void SetTempPauseDownload(bool bTempPauseDownload) { m_bTempPauseDownload = bTempPauseDownload; } - bool GetTempPauseDownload() const { return m_bTempPauseDownload; } - bool GetTempPausePostprocess() const { return m_bTempPausePostprocess; } - void SetTempPausePostprocess(bool bTempPausePostprocess) { m_bTempPausePostprocess = bTempPausePostprocess; } - void SetDownloadRate(int iRate) { m_iDownloadRate = iRate; } - int GetDownloadRate() const { return m_iDownloadRate; } - void SetResumeTime(time_t tResumeTime) { m_tResumeTime = tResumeTime; } - time_t GetResumeTime() const { return m_tResumeTime; } - void SetLocalTimeOffset(int iLocalTimeOffset) { m_iLocalTimeOffset = iLocalTimeOffset; } - int GetLocalTimeOffset() { return m_iLocalTimeOffset; } + void SetServerMode(bool serverMode) { m_serverMode = serverMode; } + bool GetServerMode() { return m_serverMode; } + void SetRemoteClientMode(bool remoteClientMode) { m_remoteClientMode = remoteClientMode; } + bool GetRemoteClientMode() { return m_remoteClientMode; } + void SetPauseDownload(bool pauseDownload) { m_pauseDownload = pauseDownload; } + bool GetPauseDownload() const { return m_pauseDownload; } + void SetPausePostProcess(bool pausePostProcess) { m_pausePostProcess = pausePostProcess; } + bool GetPausePostProcess() const { return m_pausePostProcess; } + void SetPauseScan(bool pauseScan) { m_pauseScan = pauseScan; } + bool GetPauseScan() const { return m_pauseScan; } + void SetTempPauseDownload(bool tempPauseDownload) { m_tempPauseDownload = tempPauseDownload; } + bool GetTempPauseDownload() const { return m_tempPauseDownload; } + bool GetTempPausePostprocess() const { return m_tempPausePostprocess; } + void SetTempPausePostprocess(bool tempPausePostprocess) { m_tempPausePostprocess = tempPausePostprocess; } + void SetDownloadRate(int rate) { m_downloadRate = rate; } + int GetDownloadRate() const { return m_downloadRate; } + void SetResumeTime(time_t resumeTime) { m_resumeTime = resumeTime; } + time_t GetResumeTime() const { return m_resumeTime; } + void SetLocalTimeOffset(int localTimeOffset) { m_localTimeOffset = localTimeOffset; } + int GetLocalTimeOffset() { return m_localTimeOffset; } }; extern Options* g_pOptions; diff --git a/daemon/main/Scheduler.cpp b/daemon/main/Scheduler.cpp index 857fd507..bd068670 100644 --- a/daemon/main/Scheduler.cpp +++ b/daemon/main/Scheduler.cpp @@ -47,20 +47,20 @@ #include "FeedCoordinator.h" #include "SchedulerScript.h" -Scheduler::Task::Task(int iID, int iHours, int iMinutes, int iWeekDaysBits, ECommand eCommand, const char* szParam) +Scheduler::Task::Task(int id, int hours, int minutes, int weekDaysBits, ECommand command, const char* param) { - m_iID = iID; - m_iHours = iHours; - m_iMinutes = iMinutes; - m_iWeekDaysBits = iWeekDaysBits; - m_eCommand = eCommand; - m_szParam = szParam ? strdup(szParam) : NULL; - m_tLastExecuted = 0; + m_id = id; + m_hours = hours; + m_minutes = minutes; + m_weekDaysBits = weekDaysBits; + m_command = command; + m_param = param ? strdup(param) : NULL; + m_lastExecuted = 0; } Scheduler::Task::~Task() { - free(m_szParam); + free(m_param); } @@ -68,39 +68,39 @@ Scheduler::Scheduler() { debug("Creating Scheduler"); - m_bFirstChecked = false; - m_tLastCheck = 0; - m_TaskList.clear(); + m_firstChecked = false; + m_lastCheck = 0; + m_taskList.clear(); } Scheduler::~Scheduler() { debug("Destroying Scheduler"); - for (TaskList::iterator it = m_TaskList.begin(); it != m_TaskList.end(); it++) + for (TaskList::iterator it = m_taskList.begin(); it != m_taskList.end(); it++) { delete *it; } } -void Scheduler::AddTask(Task* pTask) +void Scheduler::AddTask(Task* task) { - m_mutexTaskList.Lock(); - m_TaskList.push_back(pTask); - m_mutexTaskList.Unlock(); + m_taskListMutex.Lock(); + m_taskList.push_back(task); + m_taskListMutex.Unlock(); } -bool Scheduler::CompareTasks(Scheduler::Task* pTask1, Scheduler::Task* pTask2) +bool Scheduler::CompareTasks(Scheduler::Task* task1, Scheduler::Task* task2) { - return (pTask1->m_iHours < pTask2->m_iHours) || - ((pTask1->m_iHours == pTask2->m_iHours) && (pTask1->m_iMinutes < pTask2->m_iMinutes)); + return (task1->m_hours < task2->m_hours) || + ((task1->m_hours == task2->m_hours) && (task1->m_minutes < task2->m_minutes)); } void Scheduler::FirstCheck() { - m_mutexTaskList.Lock(); - m_TaskList.sort(CompareTasks); - m_mutexTaskList.Unlock(); + m_taskListMutex.Lock(); + m_taskList.sort(CompareTasks); + m_taskListMutex.Unlock(); // check all tasks for the last week CheckTasks(); @@ -113,14 +113,14 @@ void Scheduler::ServiceWork() return; } - if (!m_bFirstChecked) + if (!m_firstChecked) { FirstCheck(); - m_bFirstChecked = true; + m_firstChecked = true; return; } - m_bExecuteProcess = true; + m_executeProcess = true; CheckTasks(); CheckScheduledResume(); } @@ -129,141 +129,141 @@ void Scheduler::CheckTasks() { PrepareLog(); - m_mutexTaskList.Lock(); + m_taskListMutex.Lock(); - time_t tCurrent = time(NULL); + time_t current = time(NULL); - if (!m_TaskList.empty()) + if (!m_taskList.empty()) { // Detect large step changes of system time - time_t tDiff = tCurrent - m_tLastCheck; - if (tDiff > 60*90 || tDiff < 0) + time_t diff = current - m_lastCheck; + if (diff > 60*90 || diff < 0) { debug("Reset scheduled tasks (detected clock change greater than 90 minutes or negative)"); // check all tasks for the last week - m_tLastCheck = tCurrent - 60*60*24*7; - m_bExecuteProcess = false; + m_lastCheck = current - 60*60*24*7; + m_executeProcess = false; - for (TaskList::iterator it = m_TaskList.begin(); it != m_TaskList.end(); it++) + for (TaskList::iterator it = m_taskList.begin(); it != m_taskList.end(); it++) { - Task* pTask = *it; - pTask->m_tLastExecuted = 0; + Task* task = *it; + task->m_lastExecuted = 0; } } - time_t tLocalCurrent = tCurrent + g_pOptions->GetLocalTimeOffset(); - time_t tLocalLastCheck = m_tLastCheck + g_pOptions->GetLocalTimeOffset(); + time_t localCurrent = current + g_pOptions->GetLocalTimeOffset(); + time_t localLastCheck = m_lastCheck + g_pOptions->GetLocalTimeOffset(); tm tmCurrent; - gmtime_r(&tLocalCurrent, &tmCurrent); + gmtime_r(&localCurrent, &tmCurrent); tm tmLastCheck; - gmtime_r(&tLocalLastCheck, &tmLastCheck); + gmtime_r(&localLastCheck, &tmLastCheck); tm tmLoop; memcpy(&tmLoop, &tmLastCheck, sizeof(tmLastCheck)); tmLoop.tm_hour = tmCurrent.tm_hour; tmLoop.tm_min = tmCurrent.tm_min; tmLoop.tm_sec = tmCurrent.tm_sec; - time_t tLoop = Util::Timegm(&tmLoop); + time_t loop = Util::Timegm(&tmLoop); - while (tLoop <= tLocalCurrent) + while (loop <= localCurrent) { - for (TaskList::iterator it = m_TaskList.begin(); it != m_TaskList.end(); it++) + for (TaskList::iterator it = m_taskList.begin(); it != m_taskList.end(); it++) { - Task* pTask = *it; - if (pTask->m_tLastExecuted != tLoop) + Task* task = *it; + if (task->m_lastExecuted != loop) { tm tmAppoint; memcpy(&tmAppoint, &tmLoop, sizeof(tmLoop)); - tmAppoint.tm_hour = pTask->m_iHours; - tmAppoint.tm_min = pTask->m_iMinutes; + tmAppoint.tm_hour = task->m_hours; + tmAppoint.tm_min = task->m_minutes; tmAppoint.tm_sec = 0; - time_t tAppoint = Util::Timegm(&tmAppoint); + time_t appoint = Util::Timegm(&tmAppoint); - int iWeekDay = tmAppoint.tm_wday; - if (iWeekDay == 0) + int weekDay = tmAppoint.tm_wday; + if (weekDay == 0) { - iWeekDay = 7; + weekDay = 7; } - bool bWeekDayOK = pTask->m_iWeekDaysBits == 0 || (pTask->m_iWeekDaysBits & (1 << (iWeekDay - 1))); - bool bDoTask = bWeekDayOK && tLocalLastCheck < tAppoint && tAppoint <= tLocalCurrent; + bool weekDayOK = task->m_weekDaysBits == 0 || (task->m_weekDaysBits & (1 << (weekDay - 1))); + bool doTask = weekDayOK && localLastCheck < appoint && appoint <= localCurrent; //debug("TEMP: 1) m_tLastCheck=%i, tLocalCurrent=%i, tLoop=%i, tAppoint=%i, bWeekDayOK=%i, bDoTask=%i", m_tLastCheck, tLocalCurrent, tLoop, tAppoint, (int)bWeekDayOK, (int)bDoTask); - if (bDoTask) + if (doTask) { - ExecuteTask(pTask); - pTask->m_tLastExecuted = tLoop; + ExecuteTask(task); + task->m_lastExecuted = loop; } } } - tLoop += 60*60*24; // inc day - gmtime_r(&tLoop, &tmLoop); + loop += 60*60*24; // inc day + gmtime_r(&loop, &tmLoop); } } - m_tLastCheck = tCurrent; + m_lastCheck = current; - m_mutexTaskList.Unlock(); + m_taskListMutex.Unlock(); PrintLog(); } -void Scheduler::ExecuteTask(Task* pTask) +void Scheduler::ExecuteTask(Task* task) { - const char* szCommandName[] = { "Pause", "Unpause", "Pause Post-processing", "Unpause Post-processing", + const char* commandName[] = { "Pause", "Unpause", "Pause Post-processing", "Unpause Post-processing", "Set download rate", "Execute process", "Execute script", "Pause Scan", "Unpause Scan", "Enable Server", "Disable Server", "Fetch Feed" }; - debug("Executing scheduled command: %s", szCommandName[pTask->m_eCommand]); + debug("Executing scheduled command: %s", commandName[task->m_command]); - switch (pTask->m_eCommand) + switch (task->m_command) { case scDownloadRate: - if (!Util::EmptyStr(pTask->m_szParam)) + if (!Util::EmptyStr(task->m_param)) { - g_pOptions->SetDownloadRate(atoi(pTask->m_szParam) * 1024); - m_bDownloadRateChanged = true; + g_pOptions->SetDownloadRate(atoi(task->m_param) * 1024); + m_downloadRateChanged = true; } break; case scPauseDownload: case scUnpauseDownload: - g_pOptions->SetPauseDownload(pTask->m_eCommand == scPauseDownload); - m_bPauseDownloadChanged = true; + g_pOptions->SetPauseDownload(task->m_command == scPauseDownload); + m_pauseDownloadChanged = true; break; case scPausePostProcess: case scUnpausePostProcess: - g_pOptions->SetPausePostProcess(pTask->m_eCommand == scPausePostProcess); - m_bPausePostProcessChanged = true; + g_pOptions->SetPausePostProcess(task->m_command == scPausePostProcess); + m_pausePostProcessChanged = true; break; case scPauseScan: case scUnpauseScan: - g_pOptions->SetPauseScan(pTask->m_eCommand == scPauseScan); - m_bPauseScanChanged = true; + g_pOptions->SetPauseScan(task->m_command == scPauseScan); + m_pauseScanChanged = true; break; case scScript: case scProcess: - if (m_bExecuteProcess) + if (m_executeProcess) { - SchedulerScriptController::StartScript(pTask->m_szParam, pTask->m_eCommand == scProcess, pTask->m_iID); + SchedulerScriptController::StartScript(task->m_param, task->m_command == scProcess, task->m_id); } break; case scActivateServer: case scDeactivateServer: - EditServer(pTask->m_eCommand == scActivateServer, pTask->m_szParam); + EditServer(task->m_command == scActivateServer, task->m_param); break; case scFetchFeed: - if (m_bExecuteProcess) + if (m_executeProcess) { - FetchFeed(pTask->m_szParam); + FetchFeed(task->m_param); break; } } @@ -271,91 +271,91 @@ void Scheduler::ExecuteTask(Task* pTask) void Scheduler::PrepareLog() { - m_bDownloadRateChanged = false; - m_bPauseDownloadChanged = false; - m_bPausePostProcessChanged = false; - m_bPauseScanChanged = false; - m_bServerChanged = false; + m_downloadRateChanged = false; + m_pauseDownloadChanged = false; + m_pausePostProcessChanged = false; + m_pauseScanChanged = false; + m_serverChanged = false; } void Scheduler::PrintLog() { - if (m_bDownloadRateChanged) + if (m_downloadRateChanged) { info("Scheduler: setting download rate to %i KB/s", g_pOptions->GetDownloadRate() / 1024); } - if (m_bPauseDownloadChanged) + if (m_pauseDownloadChanged) { info("Scheduler: %s download", g_pOptions->GetPauseDownload() ? "pausing" : "unpausing"); } - if (m_bPausePostProcessChanged) + if (m_pausePostProcessChanged) { info("Scheduler: %s post-processing", g_pOptions->GetPausePostProcess() ? "pausing" : "unpausing"); } - if (m_bPauseScanChanged) + if (m_pauseScanChanged) { info("Scheduler: %s scan", g_pOptions->GetPauseScan() ? "pausing" : "unpausing"); } - if (m_bServerChanged) + if (m_serverChanged) { int index = 0; for (Servers::iterator it = g_pServerPool->GetServers()->begin(); it != g_pServerPool->GetServers()->end(); it++, index++) { - NewsServer* pServer = *it; - if (pServer->GetActive() != m_ServerStatusList[index]) + NewsServer* server = *it; + if (server->GetActive() != m_serverStatusList[index]) { - info("Scheduler: %s %s", pServer->GetActive() ? "activating" : "deactivating", pServer->GetName()); + info("Scheduler: %s %s", server->GetActive() ? "activating" : "deactivating", server->GetName()); } } g_pServerPool->Changed(); } } -void Scheduler::EditServer(bool bActive, const char* szServerList) +void Scheduler::EditServer(bool active, const char* serverList) { - Tokenizer tok(szServerList, ",;"); - while (const char* szServer = tok.Next()) + Tokenizer tok(serverList, ",;"); + while (const char* serverRef = tok.Next()) { - int iID = atoi(szServer); + int id = atoi(serverRef); for (Servers::iterator it = g_pServerPool->GetServers()->begin(); it != g_pServerPool->GetServers()->end(); it++) { - NewsServer* pServer = *it; - if ((iID > 0 && pServer->GetID() == iID) || - !strcasecmp(pServer->GetName(), szServer)) + NewsServer* server = *it; + if ((id > 0 && server->GetID() == id) || + !strcasecmp(server->GetName(), serverRef)) { - if (!m_bServerChanged) + if (!m_serverChanged) { // store old server status for logging - m_ServerStatusList.clear(); - m_ServerStatusList.reserve(g_pServerPool->GetServers()->size()); + m_serverStatusList.clear(); + m_serverStatusList.reserve(g_pServerPool->GetServers()->size()); for (Servers::iterator it2 = g_pServerPool->GetServers()->begin(); it2 != g_pServerPool->GetServers()->end(); it2++) { - NewsServer* pServer2 = *it2; - m_ServerStatusList.push_back(pServer2->GetActive()); + NewsServer* server2 = *it2; + m_serverStatusList.push_back(server2->GetActive()); } } - m_bServerChanged = true; - pServer->SetActive(bActive); + m_serverChanged = true; + server->SetActive(active); break; } } } } -void Scheduler::FetchFeed(const char* szFeedList) +void Scheduler::FetchFeed(const char* feedList) { - Tokenizer tok(szFeedList, ",;"); - while (const char* szFeed = tok.Next()) + Tokenizer tok(feedList, ",;"); + while (const char* feedRef = tok.Next()) { - int iID = atoi(szFeed); + int id = atoi(feedRef); for (Feeds::iterator it = g_pFeedCoordinator->GetFeeds()->begin(); it != g_pFeedCoordinator->GetFeeds()->end(); it++) { - FeedInfo* pFeed = *it; - if (pFeed->GetID() == iID || - !strcasecmp(pFeed->GetName(), szFeed) || - !strcasecmp("0", szFeed)) + FeedInfo* feed = *it; + if (feed->GetID() == id || + !strcasecmp(feed->GetName(), feedRef) || + !strcasecmp("0", feedRef)) { - g_pFeedCoordinator->FetchFeed(!strcasecmp("0", szFeed) ? 0 : pFeed->GetID()); + g_pFeedCoordinator->FetchFeed(!strcasecmp("0", feedRef) ? 0 : feed->GetID()); break; } } @@ -364,9 +364,9 @@ void Scheduler::FetchFeed(const char* szFeedList) void Scheduler::CheckScheduledResume() { - time_t tResumeTime = g_pOptions->GetResumeTime(); - time_t tCurrentTime = time(NULL); - if (tResumeTime > 0 && tCurrentTime >= tResumeTime) + time_t resumeTime = g_pOptions->GetResumeTime(); + time_t currentTime = time(NULL); + if (resumeTime > 0 && currentTime >= resumeTime) { info("Autoresume"); g_pOptions->SetResumeTime(0); diff --git a/daemon/main/Scheduler.h b/daemon/main/Scheduler.h index a015ba20..c15b0688 100644 --- a/daemon/main/Scheduler.h +++ b/daemon/main/Scheduler.h @@ -55,17 +55,17 @@ public: class Task { private: - int m_iID; - int m_iHours; - int m_iMinutes; - int m_iWeekDaysBits; - ECommand m_eCommand; - char* m_szParam; - time_t m_tLastExecuted; + int m_id; + int m_hours; + int m_minutes; + int m_weekDaysBits; + ECommand m_command; + char* m_param; + time_t m_lastExecuted; public: - Task(int iID, int iHours, int iMinutes, int iWeekDaysBits, ECommand eCommand, - const char* szParam); + Task(int id, int hours, int minutes, int weekDaysBits, ECommand command, + const char* param); ~Task(); friend class Scheduler; }; @@ -75,25 +75,25 @@ private: typedef std::list TaskList; typedef std::vector ServerStatusList; - TaskList m_TaskList; - Mutex m_mutexTaskList; - time_t m_tLastCheck; - bool m_bDownloadRateChanged; - bool m_bExecuteProcess; - bool m_bPauseDownloadChanged; - bool m_bPausePostProcessChanged; - bool m_bPauseScanChanged; - bool m_bServerChanged; - ServerStatusList m_ServerStatusList; - bool m_bFirstChecked; + TaskList m_taskList; + Mutex m_taskListMutex; + time_t m_lastCheck; + bool m_downloadRateChanged; + bool m_executeProcess; + bool m_pauseDownloadChanged; + bool m_pausePostProcessChanged; + bool m_pauseScanChanged; + bool m_serverChanged; + ServerStatusList m_serverStatusList; + bool m_firstChecked; - void ExecuteTask(Task* pTask); + void ExecuteTask(Task* task); void CheckTasks(); - static bool CompareTasks(Scheduler::Task* pTask1, Scheduler::Task* pTask2); + static bool CompareTasks(Scheduler::Task* task1, Scheduler::Task* task2); void PrepareLog(); void PrintLog(); - void EditServer(bool bActive, const char* szServerList); - void FetchFeed(const char* szFeedList); + void EditServer(bool active, const char* serverList); + void FetchFeed(const char* feedList); void CheckScheduledResume(); void FirstCheck(); @@ -104,7 +104,7 @@ protected: public: Scheduler(); ~Scheduler(); - void AddTask(Task* pTask); + void AddTask(Task* task); }; extern Scheduler* g_pScheduler; diff --git a/daemon/main/StackTrace.cpp b/daemon/main/StackTrace.cpp index 8dae841f..87f4c9ab 100644 --- a/daemon/main/StackTrace.cpp +++ b/daemon/main/StackTrace.cpp @@ -60,29 +60,29 @@ extern void ExitProc(); #ifdef DEBUG -void PrintBacktrace(PCONTEXT pContext) +void PrintBacktrace(PCONTEXT context) { HANDLE hProcess = GetCurrentProcess(); HANDLE hThread = GetCurrentThread(); - char szAppDir[MAX_PATH + 1]; - GetModuleFileName(NULL, szAppDir, sizeof(szAppDir)); - char* end = strrchr(szAppDir, PATH_SEPARATOR); + char appDir[MAX_PATH + 1]; + GetModuleFileName(NULL, appDir, sizeof(appDir)); + char* end = strrchr(appDir, PATH_SEPARATOR); if (end) *end = '\0'; SymSetOptions(SymGetOptions() | SYMOPT_LOAD_LINES | SYMOPT_FAIL_CRITICAL_ERRORS); - if (!SymInitialize(hProcess, szAppDir, TRUE)) + if (!SymInitialize(hProcess, appDir, TRUE)) { warn("Could not obtain detailed exception information: SymInitialize failed"); return; } const int MAX_NAMELEN = 1024; - IMAGEHLP_SYMBOL64* pSym = (IMAGEHLP_SYMBOL64 *) malloc(sizeof(IMAGEHLP_SYMBOL64) + MAX_NAMELEN); - memset(pSym, 0, sizeof(IMAGEHLP_SYMBOL64) + MAX_NAMELEN); - pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); - pSym->MaxNameLength = MAX_NAMELEN; + IMAGEHLP_SYMBOL64* sym = (IMAGEHLP_SYMBOL64 *) malloc(sizeof(IMAGEHLP_SYMBOL64) + MAX_NAMELEN); + memset(sym, 0, sizeof(IMAGEHLP_SYMBOL64) + MAX_NAMELEN); + sym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); + sym->MaxNameLength = MAX_NAMELEN; IMAGEHLP_LINE64 ilLine; memset(&ilLine, 0, sizeof(ilLine)); @@ -93,19 +93,19 @@ void PrintBacktrace(PCONTEXT pContext) DWORD imageType; #ifdef _M_IX86 imageType = IMAGE_FILE_MACHINE_I386; - sfStackFrame.AddrPC.Offset = pContext->Eip; + sfStackFrame.AddrPC.Offset = context->Eip; sfStackFrame.AddrPC.Mode = AddrModeFlat; - sfStackFrame.AddrFrame.Offset = pContext->Ebp; + sfStackFrame.AddrFrame.Offset = context->Ebp; sfStackFrame.AddrFrame.Mode = AddrModeFlat; - sfStackFrame.AddrStack.Offset = pContext->Esp; + sfStackFrame.AddrStack.Offset = context->Esp; sfStackFrame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 imageType = IMAGE_FILE_MACHINE_AMD64; - sfStackFrame.AddrPC.Offset = pContext->Rip; + sfStackFrame.AddrPC.Offset = context->Rip; sfStackFrame.AddrPC.Mode = AddrModeFlat; - sfStackFrame.AddrFrame.Offset = pContext->Rsp; + sfStackFrame.AddrFrame.Offset = context->Rsp; sfStackFrame.AddrFrame.Mode = AddrModeFlat; - sfStackFrame.AddrStack.Offset = pContext->Rsp; + sfStackFrame.AddrStack.Offset = context->Rsp; sfStackFrame.AddrStack.Mode = AddrModeFlat; #else warn("Could not obtain detailed exception information: platform not supported"); @@ -120,47 +120,47 @@ void PrintBacktrace(PCONTEXT pContext) return; } - if (!StackWalk64(imageType, hProcess, hThread, &sfStackFrame, pContext, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) + if (!StackWalk64(imageType, hProcess, hThread, &sfStackFrame, context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) { warn("Could not obtain detailed exception information: StackWalk64 failed"); return; } DWORD64 dwAddr = sfStackFrame.AddrPC.Offset; - char szSymName[1024]; - char szSrcFileName[1024]; - int iLineNumber = 0; + char symName[1024]; + char srcFileName[1024]; + int lineNumber = 0; DWORD64 dwSymbolDisplacement; - if (SymGetSymFromAddr64(hProcess, dwAddr, &dwSymbolDisplacement, pSym)) + if (SymGetSymFromAddr64(hProcess, dwAddr, &dwSymbolDisplacement, sym)) { - UnDecorateSymbolName(pSym->Name, szSymName, sizeof(szSymName), UNDNAME_COMPLETE); - szSymName[sizeof(szSymName) - 1] = '\0'; + UnDecorateSymbolName(sym->Name, symName, sizeof(symName), UNDNAME_COMPLETE); + symName[sizeof(symName) - 1] = '\0'; } else { - strncpy(szSymName, "", sizeof(szSymName)); + strncpy(symName, "", sizeof(symName)); } DWORD dwLineDisplacement; if (SymGetLineFromAddr64(hProcess, dwAddr, &dwLineDisplacement, &ilLine)) { - iLineNumber = ilLine.LineNumber; - char* szUseFileName = ilLine.FileName; - char* szRoot = strstr(szUseFileName, "\\daemon\\"); - if (szRoot) + lineNumber = ilLine.LineNumber; + char* useFileName = ilLine.FileName; + char* root = strstr(useFileName, "\\daemon\\"); + if (root) { - szUseFileName = szRoot; + useFileName = root; } - strncpy(szSrcFileName, szUseFileName, sizeof(szSrcFileName)); - szSrcFileName[sizeof(szSrcFileName) - 1] = '\0'; + strncpy(srcFileName, useFileName, sizeof(srcFileName)); + srcFileName[sizeof(srcFileName) - 1] = '\0'; } else { - strncpy(szSrcFileName, "", sizeof(szSymName)); + strncpy(srcFileName, "", sizeof(symName)); } - info("%s (%i) : %s", szSrcFileName, iLineNumber, szSymName); + info("%s (%i) : %s", srcFileName, lineNumber, symName); if (sfStackFrame.AddrReturn.Offset == 0) { @@ -170,15 +170,15 @@ void PrintBacktrace(PCONTEXT pContext) } #endif -LONG __stdcall ExceptionFilter(EXCEPTION_POINTERS* pExPtrs) +LONG __stdcall ExceptionFilter(EXCEPTION_POINTERS* exPtrs) { error("Unhandled Exception: code: 0x%8.8X, flags: %d, address: 0x%8.8X", - pExPtrs->ExceptionRecord->ExceptionCode, - pExPtrs->ExceptionRecord->ExceptionFlags, - pExPtrs->ExceptionRecord->ExceptionAddress); + exPtrs->ExceptionRecord->ExceptionCode, + exPtrs->ExceptionRecord->ExceptionFlags, + exPtrs->ExceptionRecord->ExceptionAddress); #ifdef DEBUG - PrintBacktrace(pExPtrs->ContextRecord); + PrintBacktrace(exPtrs->ContextRecord); #else info("Detailed exception information can be printed by debug version of NZBGet (available from download page)"); #endif @@ -250,9 +250,9 @@ void PrintBacktrace() /* * Signal handler */ -void SignalProc(int iSignal) +void SignalProc(int signum) { - switch (iSignal) + switch (signum) { case SIGINT: signal(SIGINT, SIG_DFL); // Reset the signal handler diff --git a/daemon/main/nzbget.cpp b/daemon/main/nzbget.cpp index e67559ef..19a64c6a 100644 --- a/daemon/main/nzbget.cpp +++ b/daemon/main/nzbget.cpp @@ -96,7 +96,7 @@ // Prototypes void RunMain(); -void Run(bool bReload); +void Run(bool reload); void Reload(); void Cleanup(); void ProcessClientRequest(); @@ -207,26 +207,26 @@ void RunMain() // the program is reloaded (RPC-Method "reload") in order for // config to properly load in a case relative paths are used // in command line - char szCurDir[MAX_PATH + 1]; - Util::GetCurrentDirectory(szCurDir, sizeof(szCurDir)); + char curDir[MAX_PATH + 1]; + Util::GetCurrentDirectory(curDir, sizeof(curDir)); - bool bReload = false; + bool reload = false; while (g_bReloading) { g_bReloading = false; - Util::SetCurrentDirectory(szCurDir); - Run(bReload); - bReload = true; + Util::SetCurrentDirectory(curDir); + Run(reload); + reload = true; } } -void Run(bool bReload) +void Run(bool reload) { Log::Init(); debug("nzbget %s", Util::VersionRevision()); - if (!bReload) + if (!reload) { Thread::Init(); } @@ -270,7 +270,7 @@ void Run(bool bReload) #ifdef WIN32 info("nzbget %s service-mode", Util::VersionRevision()); #else - if (!bReload) + if (!reload) { Daemonize(); } @@ -286,7 +286,7 @@ void Run(bool bReload) info("nzbget %s remote-mode", Util::VersionRevision()); } - if (!bReload) + if (!reload) { Connection::Init(); } @@ -371,17 +371,17 @@ void Run(bool bReload) // Standalone-mode if (!g_pCommandLineParser->GetServerMode()) { - const char* szCategory = g_pCommandLineParser->GetAddCategory() ? g_pCommandLineParser->GetAddCategory() : ""; - NZBFile* pNZBFile = new NZBFile(g_pCommandLineParser->GetArgFilename(), szCategory); - if (!pNZBFile->Parse()) + const char* category = g_pCommandLineParser->GetAddCategory() ? g_pCommandLineParser->GetAddCategory() : ""; + NZBFile* nzbFile = new NZBFile(g_pCommandLineParser->GetArgFilename(), category); + if (!nzbFile->Parse()) { printf("Parsing NZB-document %s failed\n\n", g_pCommandLineParser->GetArgFilename() ? g_pCommandLineParser->GetArgFilename() : "N/A"); - delete pNZBFile; + delete nzbFile; return; } - g_pScanner->InitPPParameters(szCategory, pNZBFile->GetNZBInfo()->GetParameters(), false); - g_pQueueCoordinator->AddNZBFileToQueue(pNZBFile, NULL, false); - delete pNZBFile; + g_pScanner->InitPPParameters(category, nzbFile->GetNZBInfo()->GetParameters(), false); + g_pQueueCoordinator->AddNZBFileToQueue(nzbFile, NULL, false); + delete nzbFile; } if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) @@ -463,11 +463,11 @@ void Run(bool bReload) { debug("stopping RemoteServer"); g_pRemoteServer->Stop(); - int iMaxWaitMSec = 1000; - while (g_pRemoteServer->IsRunning() && iMaxWaitMSec > 0) + int maxWaitMSec = 1000; + while (g_pRemoteServer->IsRunning() && maxWaitMSec > 0) { usleep(100 * 1000); - iMaxWaitMSec -= 100; + maxWaitMSec -= 100; } if (g_pRemoteServer->IsRunning()) { @@ -481,11 +481,11 @@ void Run(bool bReload) { debug("stopping RemoteSecureServer"); g_pRemoteSecureServer->Stop(); - int iMaxWaitMSec = 1000; - while (g_pRemoteSecureServer->IsRunning() && iMaxWaitMSec > 0) + int maxWaitMSec = 1000; + while (g_pRemoteSecureServer->IsRunning() && maxWaitMSec > 0) { usleep(100 * 1000); - iMaxWaitMSec -= 100; + maxWaitMSec -= 100; } if (g_pRemoteSecureServer->IsRunning()) { @@ -523,26 +523,26 @@ protected: } #endif - virtual void AddNewsServer(int iID, bool bActive, const char* szName, const char* szHost, - int iPort, const char* szUser, const char* szPass, bool bJoinGroup, - bool bTLS, const char* szCipher, int iMaxConnections, int iRetention, - int iLevel, int iGroup) + virtual void AddNewsServer(int id, bool active, const char* name, const char* host, + int port, const char* user, const char* pass, bool joinGroup, + bool tLS, const char* cipher, int maxConnections, int retention, + int level, int group) { - g_pServerPool->AddServer(new NewsServer(iID, bActive, szName, szHost, iPort, szUser, szPass, bJoinGroup, - bTLS, szCipher, iMaxConnections, iRetention, iLevel, iGroup)); + g_pServerPool->AddServer(new NewsServer(id, active, name, host, port, user, pass, joinGroup, + tLS, cipher, maxConnections, retention, level, group)); } - virtual void AddFeed(int iID, const char* szName, const char* szUrl, int iInterval, - const char* szFilter, bool bBacklog, bool bPauseNzb, const char* szCategory, - int iPriority, const char* szFeedScript) + virtual void AddFeed(int id, const char* name, const char* url, int interval, + const char* filter, bool backlog, bool pauseNzb, const char* category, + int priority, const char* feedScript) { - g_pFeedCoordinator->AddFeed(new FeedInfo(iID, szName, szUrl, bBacklog, iInterval, szFilter, bPauseNzb, szCategory, iPriority, szFeedScript)); + g_pFeedCoordinator->AddFeed(new FeedInfo(id, name, url, backlog, interval, filter, pauseNzb, category, priority, feedScript)); } - virtual void AddTask(int iID, int iHours, int iMinutes, int iWeekDaysBits, - Options::ESchedulerCommand eCommand, const char* szParam) + virtual void AddTask(int id, int hours, int minutes, int weekDaysBits, + Options::ESchedulerCommand command, const char* param) { - g_pScheduler->AddTask(new Scheduler::Task(iID, iHours, iMinutes, iWeekDaysBits, (Scheduler::ECommand)eCommand, szParam)); + g_pScheduler->AddTask(new Scheduler::Task(id, hours, minutes, weekDaysBits, (Scheduler::ECommand)command, param)); } } g_OptionsExtender; @@ -609,11 +609,11 @@ void ProcessClientRequest() break; case CommandLineParser::opClientRequestDownloadPause: - Client->RequestServerPauseUnpause(true, eRemotePauseUnpauseActionDownload); + Client->RequestServerPauseUnpause(true, remotePauseUnpauseActionDownload); break; case CommandLineParser::opClientRequestDownloadUnpause: - Client->RequestServerPauseUnpause(false, eRemotePauseUnpauseActionDownload); + Client->RequestServerPauseUnpause(false, remotePauseUnpauseActionDownload); break; case CommandLineParser::opClientRequestSetRate: @@ -628,7 +628,7 @@ void ProcessClientRequest() Client->RequestServerEditQueue((DownloadQueue::EEditAction)g_pCommandLineParser->GetEditQueueAction(), g_pCommandLineParser->GetEditQueueOffset(), g_pCommandLineParser->GetEditQueueText(), g_pCommandLineParser->GetEditQueueIDList(), g_pCommandLineParser->GetEditQueueIDCount(), - g_pCommandLineParser->GetEditQueueNameList(), (eRemoteMatchMode)g_pCommandLineParser->GetMatchMode()); + g_pCommandLineParser->GetEditQueueNameList(), (remoteMatchMode)g_pCommandLineParser->GetMatchMode()); break; case CommandLineParser::opClientRequestLog: @@ -670,19 +670,19 @@ void ProcessClientRequest() break; case CommandLineParser::opClientRequestPostPause: - Client->RequestServerPauseUnpause(true, eRemotePauseUnpauseActionPostProcess); + Client->RequestServerPauseUnpause(true, remotePauseUnpauseActionPostProcess); break; case CommandLineParser::opClientRequestPostUnpause: - Client->RequestServerPauseUnpause(false, eRemotePauseUnpauseActionPostProcess); + Client->RequestServerPauseUnpause(false, remotePauseUnpauseActionPostProcess); break; case CommandLineParser::opClientRequestScanPause: - Client->RequestServerPauseUnpause(true, eRemotePauseUnpauseActionScan); + Client->RequestServerPauseUnpause(true, remotePauseUnpauseActionScan); break; case CommandLineParser::opClientRequestScanUnpause: - Client->RequestServerPauseUnpause(false, eRemotePauseUnpauseActionScan); + Client->RequestServerPauseUnpause(false, remotePauseUnpauseActionScan); break; case CommandLineParser::opClientRequestHistory: @@ -706,18 +706,18 @@ void ProcessWebGet() downloader.SetOutputFilename(g_pCommandLineParser->GetWebGetFilename()); downloader.SetInfoName("WebGet"); - WebDownloader::EStatus eStatus = downloader.DownloadWithRedirects(5); - bool bOK = eStatus == WebDownloader::adFinished; + WebDownloader::EStatus status = downloader.DownloadWithRedirects(5); + bool ok = status == WebDownloader::adFinished; - exit(bOK ? 0 : 1); + exit(ok ? 0 : 1); } void ProcessSigVerify() { #ifdef HAVE_OPENSSL - bool bOK = Maintenance::VerifySignature(g_pCommandLineParser->GetLastArg(), + bool ok = Maintenance::VerifySignature(g_pCommandLineParser->GetLastArg(), g_pCommandLineParser->GetSigFilename(), g_pCommandLineParser->GetPubKeyFilename()); - exit(bOK ? 93 : 1); + exit(ok ? 93 : 1); #else printf("ERROR: Could not verify signature, the program was compiled without OpenSSL support\n"); exit(1); diff --git a/daemon/nntp/ArticleDownloader.cpp b/daemon/nntp/ArticleDownloader.cpp index f03a5798..34766beb 100644 --- a/daemon/nntp/ArticleDownloader.cpp +++ b/daemon/nntp/ArticleDownloader.cpp @@ -58,14 +58,14 @@ ArticleDownloader::ArticleDownloader() { debug("Creating ArticleDownloader"); - m_szInfoName = NULL; - m_szConnectionName[0] = '\0'; - m_pConnection = NULL; - m_eStatus = adUndefined; - m_eFormat = Decoder::efUnknown; - m_szArticleFilename = NULL; - m_iDownloadedSize = 0; - m_ArticleWriter.SetOwner(this); + m_infoName = NULL; + m_connectionName[0] = '\0'; + m_connection = NULL; + m_status = adUndefined; + m_format = Decoder::efUnknown; + m_articleFilename = NULL; + m_downloadedSize = 0; + m_articleWriter.SetOwner(this); SetLastUpdateTimeNow(); } @@ -73,14 +73,14 @@ ArticleDownloader::~ArticleDownloader() { debug("Destroying ArticleDownloader"); - free(m_szInfoName); - free(m_szArticleFilename); + free(m_infoName); + free(m_articleFilename); } -void ArticleDownloader::SetInfoName(const char* szInfoName) +void ArticleDownloader::SetInfoName(const char* infoName) { - m_szInfoName = strdup(szInfoName); - m_ArticleWriter.SetInfoName(m_szInfoName); + m_infoName = strdup(infoName); + m_articleWriter.SetInfoName(m_infoName); } /* @@ -110,113 +110,113 @@ void ArticleDownloader::Run() SetStatus(adRunning); - m_ArticleWriter.SetFileInfo(m_pFileInfo); - m_ArticleWriter.SetArticleInfo(m_pArticleInfo); - m_ArticleWriter.Prepare(); + m_articleWriter.SetFileInfo(m_fileInfo); + m_articleWriter.SetArticleInfo(m_articleInfo); + m_articleWriter.Prepare(); EStatus Status = adFailed; - int iRetries = g_pOptions->GetRetries() > 0 ? g_pOptions->GetRetries() : 1; - int iRemainedRetries = iRetries; + int retries = g_pOptions->GetRetries() > 0 ? g_pOptions->GetRetries() : 1; + int remainedRetries = retries; Servers failedServers; failedServers.reserve(g_pServerPool->GetServers()->size()); - NewsServer* pWantServer = NULL; - NewsServer* pLastServer = NULL; - int iLevel = 0; - int iServerConfigGeneration = g_pServerPool->GetGeneration(); - bool bForce = m_pFileInfo->GetNZBInfo()->GetForcePriority(); + NewsServer* wantServer = NULL; + NewsServer* lastServer = NULL; + int level = 0; + int serverConfigGeneration = g_pServerPool->GetGeneration(); + bool force = m_fileInfo->GetNZBInfo()->GetForcePriority(); while (!IsStopped()) { Status = adFailed; SetStatus(adWaiting); - while (!m_pConnection && !(IsStopped() || iServerConfigGeneration != g_pServerPool->GetGeneration())) + while (!m_connection && !(IsStopped() || serverConfigGeneration != g_pServerPool->GetGeneration())) { - m_pConnection = g_pServerPool->GetConnection(iLevel, pWantServer, &failedServers); + m_connection = g_pServerPool->GetConnection(level, wantServer, &failedServers); usleep(5 * 1000); } SetLastUpdateTimeNow(); SetStatus(adRunning); - if (IsStopped() || (g_pOptions->GetPauseDownload() && !bForce) || - (g_pOptions->GetTempPauseDownload() && !m_pFileInfo->GetExtraPriority()) || - iServerConfigGeneration != g_pServerPool->GetGeneration()) + if (IsStopped() || (g_pOptions->GetPauseDownload() && !force) || + (g_pOptions->GetTempPauseDownload() && !m_fileInfo->GetExtraPriority()) || + serverConfigGeneration != g_pServerPool->GetGeneration()) { Status = adRetry; break; } - pLastServer = m_pConnection->GetNewsServer(); + lastServer = m_connection->GetNewsServer(); - m_pConnection->SetSuppressErrors(false); + m_connection->SetSuppressErrors(false); - snprintf(m_szConnectionName, sizeof(m_szConnectionName), "%s (%s)", - m_pConnection->GetNewsServer()->GetName(), m_pConnection->GetHost()); - m_szConnectionName[sizeof(m_szConnectionName) - 1] = '\0'; + snprintf(m_connectionName, sizeof(m_connectionName), "%s (%s)", + m_connection->GetNewsServer()->GetName(), m_connection->GetHost()); + m_connectionName[sizeof(m_connectionName) - 1] = '\0'; // check server retention - bool bRetentionFailure = m_pConnection->GetNewsServer()->GetRetention() > 0 && - (time(NULL) - m_pFileInfo->GetTime()) / 86400 > m_pConnection->GetNewsServer()->GetRetention(); - if (bRetentionFailure) + bool retentionFailure = m_connection->GetNewsServer()->GetRetention() > 0 && + (time(NULL) - m_fileInfo->GetTime()) / 86400 > m_connection->GetNewsServer()->GetRetention(); + if (retentionFailure) { detail("Article %s @ %s failed: out of server retention (file age: %i, configured retention: %i)", - m_szInfoName, m_szConnectionName, - (time(NULL) - m_pFileInfo->GetTime()) / 86400, - m_pConnection->GetNewsServer()->GetRetention()); + m_infoName, m_connectionName, + (time(NULL) - m_fileInfo->GetTime()) / 86400, + m_connection->GetNewsServer()->GetRetention()); Status = adFailed; FreeConnection(true); } - if (m_pConnection && !IsStopped()) + if (m_connection && !IsStopped()) { - detail("Downloading %s @ %s", m_szInfoName, m_szConnectionName); + detail("Downloading %s @ %s", m_infoName, m_connectionName); } // test connection - bool bConnected = m_pConnection && m_pConnection->Connect(); - if (bConnected && !IsStopped()) + bool connected = m_connection && m_connection->Connect(); + if (connected && !IsStopped()) { - NewsServer* pNewsServer = m_pConnection->GetNewsServer(); + NewsServer* newsServer = m_connection->GetNewsServer(); // Download article Status = Download(); if (Status == adFinished || Status == adFailed || Status == adNotFound || Status == adCrcError) { - m_ServerStats.StatOp(pNewsServer->GetID(), Status == adFinished ? 1 : 0, Status == adFinished ? 0 : 1, ServerStatList::soSet); + m_serverStats.StatOp(newsServer->GetID(), Status == adFinished ? 1 : 0, Status == adFinished ? 0 : 1, ServerStatList::soSet); } } - if (m_pConnection) + if (m_connection) { AddServerData(); } - if (!bConnected && m_pConnection) + if (!connected && m_connection) { - detail("Article %s @ %s failed: could not establish connection", m_szInfoName, m_szConnectionName); + detail("Article %s @ %s failed: could not establish connection", m_infoName, m_connectionName); } if (Status == adConnectError) { - bConnected = false; + connected = false; Status = adFailed; } - if (bConnected && Status == adFailed) + if (connected && Status == adFailed) { - iRemainedRetries--; + remainedRetries--; } - if (!bConnected && m_pConnection && !IsStopped()) + if (!connected && m_connection && !IsStopped()) { - g_pServerPool->BlockServer(pLastServer); + g_pServerPool->BlockServer(lastServer); } - pWantServer = NULL; - if (bConnected && Status == adFailed && iRemainedRetries > 0 && !bRetentionFailure) + wantServer = NULL; + if (connected && Status == adFailed && remainedRetries > 0 && !retentionFailure) { - pWantServer = pLastServer; + wantServer = lastServer; } else { @@ -228,72 +228,72 @@ void ArticleDownloader::Run() break; } - if (IsStopped() || (g_pOptions->GetPauseDownload() && !bForce) || - (g_pOptions->GetTempPauseDownload() && !m_pFileInfo->GetExtraPriority()) || - iServerConfigGeneration != g_pServerPool->GetGeneration()) + if (IsStopped() || (g_pOptions->GetPauseDownload() && !force) || + (g_pOptions->GetTempPauseDownload() && !m_fileInfo->GetExtraPriority()) || + serverConfigGeneration != g_pServerPool->GetGeneration()) { Status = adRetry; break; } - if (!pWantServer && (bConnected || bRetentionFailure)) + if (!wantServer && (connected || retentionFailure)) { - failedServers.push_back(pLastServer); + failedServers.push_back(lastServer); // if all servers from current level were tried, increase level // if all servers from all levels were tried, break the loop with failure status - bool bAllServersOnLevelFailed = true; + bool allServersOnLevelFailed = true; for (Servers::iterator it = g_pServerPool->GetServers()->begin(); it != g_pServerPool->GetServers()->end(); it++) { - NewsServer* pCandidateServer = *it; - if (pCandidateServer->GetNormLevel() == iLevel) + NewsServer* candidateServer = *it; + if (candidateServer->GetNormLevel() == level) { - bool bServerFailed = !pCandidateServer->GetActive() || pCandidateServer->GetMaxConnections() == 0; - if (!bServerFailed) + bool serverFailed = !candidateServer->GetActive() || candidateServer->GetMaxConnections() == 0; + if (!serverFailed) { for (Servers::iterator it = failedServers.begin(); it != failedServers.end(); it++) { - NewsServer* pIgnoreServer = *it; - if (pIgnoreServer == pCandidateServer || - (pIgnoreServer->GetGroup() > 0 && pIgnoreServer->GetGroup() == pCandidateServer->GetGroup() && - pIgnoreServer->GetNormLevel() == pCandidateServer->GetNormLevel())) + NewsServer* ignoreServer = *it; + if (ignoreServer == candidateServer || + (ignoreServer->GetGroup() > 0 && ignoreServer->GetGroup() == candidateServer->GetGroup() && + ignoreServer->GetNormLevel() == candidateServer->GetNormLevel())) { - bServerFailed = true; + serverFailed = true; break; } } } - if (!bServerFailed) + if (!serverFailed) { - bAllServersOnLevelFailed = false; + allServersOnLevelFailed = false; break; } } } - if (bAllServersOnLevelFailed) + if (allServersOnLevelFailed) { - if (iLevel < g_pServerPool->GetMaxNormLevel()) + if (level < g_pServerPool->GetMaxNormLevel()) { - detail("Article %s @ all level %i servers failed, increasing level", m_szInfoName, iLevel); - iLevel++; + detail("Article %s @ all level %i servers failed, increasing level", m_infoName, level); + level++; } else { - detail("Article %s @ all servers failed", m_szInfoName); + detail("Article %s @ all servers failed", m_infoName); Status = adFailed; break; } } - iRemainedRetries = iRetries; + remainedRetries = retries; } } FreeConnection(Status == adFinished); - if (m_ArticleWriter.GetDuplicate()) + if (m_articleWriter.GetDuplicate()) { Status = adFinished; } @@ -305,13 +305,13 @@ void ArticleDownloader::Run() if (IsStopped()) { - detail("Download %s cancelled", m_szInfoName); + detail("Download %s cancelled", m_infoName); Status = adRetry; } if (Status == adFailed) { - detail("Download %s failed", m_szInfoName); + detail("Download %s failed", m_infoName); } SetStatus(Status); @@ -322,24 +322,24 @@ void ArticleDownloader::Run() ArticleDownloader::EStatus ArticleDownloader::Download() { - const char* szResponse = NULL; + const char* response = NULL; EStatus Status = adRunning; - m_bWritingStarted = false; - m_pArticleInfo->SetCrc(0); + m_writingStarted = false; + m_articleInfo->SetCrc(0); - if (m_pConnection->GetNewsServer()->GetJoinGroup()) + if (m_connection->GetNewsServer()->GetJoinGroup()) { // change group - for (FileInfo::Groups::iterator it = m_pFileInfo->GetGroups()->begin(); it != m_pFileInfo->GetGroups()->end(); it++) + for (FileInfo::Groups::iterator it = m_fileInfo->GetGroups()->begin(); it != m_fileInfo->GetGroups()->end(); it++) { - szResponse = m_pConnection->JoinGroup(*it); - if (szResponse && !strncmp(szResponse, "2", 1)) + response = m_connection->JoinGroup(*it); + if (response && !strncmp(response, "2", 1)) { break; } } - Status = CheckResponse(szResponse, "could not join group"); + Status = CheckResponse(response, "could not join group"); if (Status != adFinished) { return Status; @@ -348,19 +348,19 @@ ArticleDownloader::EStatus ArticleDownloader::Download() // retrieve article char tmp[1024]; - snprintf(tmp, 1024, "ARTICLE %s\r\n", m_pArticleInfo->GetMessageID()); + snprintf(tmp, 1024, "ARTICLE %s\r\n", m_articleInfo->GetMessageID()); tmp[1024-1] = '\0'; for (int retry = 3; retry > 0; retry--) { - szResponse = m_pConnection->Request(tmp); - if ((szResponse && !strncmp(szResponse, "2", 1)) || m_pConnection->GetAuthError()) + response = m_connection->Request(tmp); + if ((response && !strncmp(response, "2", 1)) || m_connection->GetAuthError()) { break; } } - Status = CheckResponse(szResponse, "could not fetch article"); + Status = CheckResponse(response, "could not fetch article"); if (Status != adFinished) { return Status; @@ -368,22 +368,22 @@ ArticleDownloader::EStatus ArticleDownloader::Download() if (g_pOptions->GetDecode()) { - m_YDecoder.Clear(); - m_YDecoder.SetCrcCheck(g_pOptions->GetCrcCheck()); - m_UDecoder.Clear(); + m_yDecoder.Clear(); + m_yDecoder.SetCrcCheck(g_pOptions->GetCrcCheck()); + m_uDecoder.Clear(); } - bool bBody = false; - bool bEnd = false; + bool body = false; + bool end = false; const int LineBufSize = 1024*10; - char* szLineBuf = (char*)malloc(LineBufSize); + char* lineBuf = (char*)malloc(LineBufSize); Status = adRunning; while (!IsStopped()) { - time_t tOldTime = m_tLastUpdateTime; + time_t oldTime = m_lastUpdateTime; SetLastUpdateTimeNow(); - if (tOldTime != m_tLastUpdateTime) + if (oldTime != m_lastUpdateTime) { AddServerData(); } @@ -397,10 +397,10 @@ ArticleDownloader::EStatus ArticleDownloader::Download() usleep(10 * 1000); } - int iLen = 0; - char* line = m_pConnection->ReadLine(szLineBuf, LineBufSize, &iLen); + int len = 0; + char* line = m_connection->ReadLine(lineBuf, LineBufSize, &len); - g_pStatMeter->AddSpeedReading(iLen); + g_pStatMeter->AddSpeedReading(len); if (g_pOptions->GetAccurateRate()) { AddServerData(); @@ -411,7 +411,7 @@ ArticleDownloader::EStatus ArticleDownloader::Download() { if (!IsStopped()) { - detail("Article %s @ %s failed: Unexpected end of article", m_szInfoName, m_szConnectionName); + detail("Article %s @ %s failed: Unexpected end of article", m_infoName, m_connectionName); } Status = adFailed; break; @@ -420,7 +420,7 @@ ArticleDownloader::EStatus ArticleDownloader::Download() //detect end of article if (!strcmp(line, ".\r\n") || !strcmp(line, ".\n")) { - bEnd = true; + end = true; break; } @@ -428,55 +428,55 @@ ArticleDownloader::EStatus ArticleDownloader::Download() if (!strncmp(line, "..", 2)) { line++; - iLen--; + len--; } - if (!bBody) + if (!body) { // detect body of article if (*line == '\r' || *line == '\n') { - bBody = true; + body = true; } // check id of returned article else if (!strncmp(line, "Message-ID: ", 12)) { char* p = line + 12; - if (strncmp(p, m_pArticleInfo->GetMessageID(), strlen(m_pArticleInfo->GetMessageID()))) + if (strncmp(p, m_articleInfo->GetMessageID(), strlen(m_articleInfo->GetMessageID()))) { if (char* e = strrchr(p, '\r')) *e = '\0'; // remove trailing CR-character - detail("Article %s @ %s failed: Wrong message-id, expected %s, returned %s", m_szInfoName, - m_szConnectionName, m_pArticleInfo->GetMessageID(), p); + detail("Article %s @ %s failed: Wrong message-id, expected %s, returned %s", m_infoName, + m_connectionName, m_articleInfo->GetMessageID(), p); Status = adFailed; break; } } } - if (m_eFormat == Decoder::efUnknown && g_pOptions->GetDecode()) + if (m_format == Decoder::efUnknown && g_pOptions->GetDecode()) { - m_eFormat = Decoder::DetectFormat(line, iLen); - if (m_eFormat != Decoder::efUnknown) + m_format = Decoder::DetectFormat(line, len); + if (m_format != Decoder::efUnknown) { // sometimes news servers misbehave and send article body without new line separator between headers and body // if we found decoder signature we know the body is already arrived - bBody = true; + body = true; } } // write to output file - if (((bBody && m_eFormat != Decoder::efUnknown) || !g_pOptions->GetDecode()) && !Write(line, iLen)) + if (((body && m_format != Decoder::efUnknown) || !g_pOptions->GetDecode()) && !Write(line, len)) { Status = adFatalError; break; } } - free(szLineBuf); + free(lineBuf); - if (!bEnd && Status == adRunning && !IsStopped()) + if (!end && Status == adRunning && !IsStopped()) { - detail("Article %s @ %s failed: article incomplete", m_szInfoName, m_szConnectionName); + detail("Article %s @ %s failed: article incomplete", m_infoName, m_connectionName); Status = adFailed; } @@ -491,41 +491,41 @@ ArticleDownloader::EStatus ArticleDownloader::Download() Status = DecodeCheck(); } - if (m_bWritingStarted) + if (m_writingStarted) { - m_ArticleWriter.Finish(Status == adFinished); + m_articleWriter.Finish(Status == adFinished); } if (Status == adFinished) { - detail("Successfully downloaded %s", m_szInfoName); + detail("Successfully downloaded %s", m_infoName); } return Status; } -ArticleDownloader::EStatus ArticleDownloader::CheckResponse(const char* szResponse, const char* szComment) +ArticleDownloader::EStatus ArticleDownloader::CheckResponse(const char* response, const char* comment) { - if (!szResponse) + if (!response) { if (!IsStopped()) { detail("Article %s @ %s failed, %s: Connection closed by remote host", - m_szInfoName, m_szConnectionName, szComment); + m_infoName, m_connectionName, comment); } return adConnectError; } - else if (m_pConnection->GetAuthError() || !strncmp(szResponse, "400", 3) || !strncmp(szResponse, "499", 3)) + else if (m_connection->GetAuthError() || !strncmp(response, "400", 3) || !strncmp(response, "499", 3)) { - detail("Article %s @ %s failed, %s: %s", m_szInfoName, m_szConnectionName, szComment, szResponse); + detail("Article %s @ %s failed, %s: %s", m_infoName, m_connectionName, comment, response); return adConnectError; } - else if (!strncmp(szResponse, "41", 2) || !strncmp(szResponse, "42", 2) || !strncmp(szResponse, "43", 2)) + else if (!strncmp(response, "41", 2) || !strncmp(response, "42", 2) || !strncmp(response, "43", 2)) { - detail("Article %s @ %s failed, %s: %s", m_szInfoName, m_szConnectionName, szComment, szResponse); + detail("Article %s @ %s failed, %s: %s", m_infoName, m_connectionName, comment, response); return adNotFound; } - else if (!strncmp(szResponse, "2", 1)) + else if (!strncmp(response, "2", 1)) { // OK return adFinished; @@ -533,122 +533,122 @@ ArticleDownloader::EStatus ArticleDownloader::CheckResponse(const char* szRespon else { // unknown error, no special handling - detail("Article %s @ %s failed, %s: %s", m_szInfoName, m_szConnectionName, szComment, szResponse); + detail("Article %s @ %s failed, %s: %s", m_infoName, m_connectionName, comment, response); return adFailed; } } -bool ArticleDownloader::Write(char* szLine, int iLen) +bool ArticleDownloader::Write(char* line, int len) { - const char* szArticleFilename = NULL; - long long iArticleFileSize = 0; - long long iArticleOffset = 0; - int iArticleSize = 0; + const char* articleFilename = NULL; + long long articleFileSize = 0; + long long articleOffset = 0; + int articleSize = 0; if (g_pOptions->GetDecode()) { - if (m_eFormat == Decoder::efYenc) + if (m_format == Decoder::efYenc) { - iLen = m_YDecoder.DecodeBuffer(szLine, iLen); - szArticleFilename = m_YDecoder.GetArticleFilename(); - iArticleFileSize = m_YDecoder.GetSize(); + len = m_yDecoder.DecodeBuffer(line, len); + articleFilename = m_yDecoder.GetArticleFilename(); + articleFileSize = m_yDecoder.GetSize(); } - else if (m_eFormat == Decoder::efUx) + else if (m_format == Decoder::efUx) { - iLen = m_UDecoder.DecodeBuffer(szLine, iLen); - szArticleFilename = m_UDecoder.GetArticleFilename(); + len = m_uDecoder.DecodeBuffer(line, len); + articleFilename = m_uDecoder.GetArticleFilename(); } else { - detail("Decoding %s failed: unsupported encoding", m_szInfoName); + detail("Decoding %s failed: unsupported encoding", m_infoName); return false; } - if (iLen > 0 && m_eFormat == Decoder::efYenc) + if (len > 0 && m_format == Decoder::efYenc) { - if (m_YDecoder.GetBegin() == 0 || m_YDecoder.GetEnd() == 0) + if (m_yDecoder.GetBegin() == 0 || m_yDecoder.GetEnd() == 0) { return false; } - iArticleOffset = m_YDecoder.GetBegin() - 1; - iArticleSize = (int)(m_YDecoder.GetEnd() - m_YDecoder.GetBegin() + 1); + articleOffset = m_yDecoder.GetBegin() - 1; + articleSize = (int)(m_yDecoder.GetEnd() - m_yDecoder.GetBegin() + 1); } } - if (!m_bWritingStarted && iLen > 0) + if (!m_writingStarted && len > 0) { - if (!m_ArticleWriter.Start(m_eFormat, szArticleFilename, iArticleFileSize, iArticleOffset, iArticleSize)) + if (!m_articleWriter.Start(m_format, articleFilename, articleFileSize, articleOffset, articleSize)) { return false; } - m_bWritingStarted = true; + m_writingStarted = true; } - bool bOK = iLen == 0 || m_ArticleWriter.Write(szLine, iLen); + bool ok = len == 0 || m_articleWriter.Write(line, len); - return bOK; + return ok; } ArticleDownloader::EStatus ArticleDownloader::DecodeCheck() { if (g_pOptions->GetDecode()) { - Decoder* pDecoder = NULL; - if (m_eFormat == Decoder::efYenc) + Decoder* decoder = NULL; + if (m_format == Decoder::efYenc) { - pDecoder = &m_YDecoder; + decoder = &m_yDecoder; } - else if (m_eFormat == Decoder::efUx) + else if (m_format == Decoder::efUx) { - pDecoder = &m_UDecoder; + decoder = &m_uDecoder; } else { - detail("Decoding %s failed: no binary data or unsupported encoding format", m_szInfoName); + detail("Decoding %s failed: no binary data or unsupported encoding format", m_infoName); return adFailed; } - Decoder::EStatus eStatus = pDecoder->Check(); + Decoder::EStatus status = decoder->Check(); - if (eStatus == Decoder::eFinished) + if (status == Decoder::dsFinished) { - if (pDecoder->GetArticleFilename()) + if (decoder->GetArticleFilename()) { - free(m_szArticleFilename); - m_szArticleFilename = strdup(pDecoder->GetArticleFilename()); + free(m_articleFilename); + m_articleFilename = strdup(decoder->GetArticleFilename()); } - if (m_eFormat == Decoder::efYenc) + if (m_format == Decoder::efYenc) { - m_pArticleInfo->SetCrc(g_pOptions->GetCrcCheck() ? - m_YDecoder.GetCalculatedCrc() : m_YDecoder.GetExpectedCrc()); + m_articleInfo->SetCrc(g_pOptions->GetCrcCheck() ? + m_yDecoder.GetCalculatedCrc() : m_yDecoder.GetExpectedCrc()); } return adFinished; } - else if (eStatus == Decoder::eCrcError) + else if (status == Decoder::dsCrcError) { - detail("Decoding %s failed: CRC-Error", m_szInfoName); + detail("Decoding %s failed: CRC-Error", m_infoName); return adCrcError; } - else if (eStatus == Decoder::eArticleIncomplete) + else if (status == Decoder::dsArticleIncomplete) { - detail("Decoding %s failed: article incomplete", m_szInfoName); + detail("Decoding %s failed: article incomplete", m_infoName); return adFailed; } - else if (eStatus == Decoder::eInvalidSize) + else if (status == Decoder::dsInvalidSize) { - detail("Decoding %s failed: size mismatch", m_szInfoName); + detail("Decoding %s failed: size mismatch", m_infoName); return adFailed; } - else if (eStatus == Decoder::eNoBinaryData) + else if (status == Decoder::dsNoBinaryData) { - detail("Decoding %s failed: no binary data found", m_szInfoName); + detail("Decoding %s failed: no binary data found", m_infoName); return adFailed; } else { - detail("Decoding %s failed", m_szInfoName); + detail("Decoding %s failed", m_infoName); return adFailed; } } @@ -660,65 +660,65 @@ ArticleDownloader::EStatus ArticleDownloader::DecodeCheck() void ArticleDownloader::LogDebugInfo() { - char szTime[50]; + char time[50]; #ifdef HAVE_CTIME_R_3 - ctime_r(&m_tLastUpdateTime, szTime, 50); + ctime_r(&m_lastUpdateTime, time, 50); #else - ctime_r(&m_tLastUpdateTime, szTime); + ctime_r(&m_lastUpdateTime, time); #endif - info(" Download: Status=%i, LastUpdateTime=%s, InfoName=%s", m_eStatus, szTime, m_szInfoName); + info(" Download: Status=%i, LastUpdateTime=%s, InfoName=%s", m_status, time, m_infoName); } void ArticleDownloader::Stop() { debug("Trying to stop ArticleDownloader"); Thread::Stop(); - m_mutexConnection.Lock(); - if (m_pConnection) + m_connectionMutex.Lock(); + if (m_connection) { - m_pConnection->SetSuppressErrors(true); - m_pConnection->Cancel(); + m_connection->SetSuppressErrors(true); + m_connection->Cancel(); } - m_mutexConnection.Unlock(); + m_connectionMutex.Unlock(); debug("ArticleDownloader stopped successfully"); } bool ArticleDownloader::Terminate() { - NNTPConnection* pConnection = m_pConnection; + NNTPConnection* connection = m_connection; bool terminated = Kill(); - if (terminated && pConnection) + if (terminated && connection) { debug("Terminating connection"); - pConnection->SetSuppressErrors(true); - pConnection->Cancel(); - pConnection->Disconnect(); - g_pStatMeter->AddServerData(pConnection->FetchTotalBytesRead(), pConnection->GetNewsServer()->GetID()); - g_pServerPool->FreeConnection(pConnection, true); + connection->SetSuppressErrors(true); + connection->Cancel(); + connection->Disconnect(); + g_pStatMeter->AddServerData(connection->FetchTotalBytesRead(), connection->GetNewsServer()->GetID()); + g_pServerPool->FreeConnection(connection, true); } return terminated; } -void ArticleDownloader::FreeConnection(bool bKeepConnected) +void ArticleDownloader::FreeConnection(bool keepConnected) { - if (m_pConnection) + if (m_connection) { debug("Releasing connection"); - m_mutexConnection.Lock(); - if (!bKeepConnected || m_pConnection->GetStatus() == Connection::csCancelled) + m_connectionMutex.Lock(); + if (!keepConnected || m_connection->GetStatus() == Connection::csCancelled) { - m_pConnection->Disconnect(); + m_connection->Disconnect(); } AddServerData(); - g_pServerPool->FreeConnection(m_pConnection, true); - m_pConnection = NULL; - m_mutexConnection.Unlock(); + g_pServerPool->FreeConnection(m_connection, true); + m_connection = NULL; + m_connectionMutex.Unlock(); } } void ArticleDownloader::AddServerData() { - int iBytesRead = m_pConnection->FetchTotalBytesRead(); - g_pStatMeter->AddServerData(iBytesRead, m_pConnection->GetNewsServer()->GetID()); - m_iDownloadedSize += iBytesRead; + int bytesRead = m_connection->FetchTotalBytesRead(); + g_pStatMeter->AddServerData(bytesRead, m_connection->GetNewsServer()->GetID()); + m_downloadedSize += bytesRead; } diff --git a/daemon/nntp/ArticleDownloader.h b/daemon/nntp/ArticleDownloader.h index cac70aad..2120953a 100644 --- a/daemon/nntp/ArticleDownloader.h +++ b/daemon/nntp/ArticleDownloader.h @@ -56,60 +56,60 @@ public: class ArticleWriterImpl : public ArticleWriter { private: - ArticleDownloader* m_pOwner; + ArticleDownloader* m_owner; protected: - virtual void SetLastUpdateTimeNow() { m_pOwner->SetLastUpdateTimeNow(); } + virtual void SetLastUpdateTimeNow() { m_owner->SetLastUpdateTimeNow(); } public: - void SetOwner(ArticleDownloader* pOwner) { m_pOwner = pOwner; } + void SetOwner(ArticleDownloader* owner) { m_owner = owner; } }; private: - FileInfo* m_pFileInfo; - ArticleInfo* m_pArticleInfo; - NNTPConnection* m_pConnection; - EStatus m_eStatus; - Mutex m_mutexConnection; - char* m_szInfoName; - char m_szConnectionName[250]; - char* m_szArticleFilename; - time_t m_tLastUpdateTime; - Decoder::EFormat m_eFormat; - YDecoder m_YDecoder; - UDecoder m_UDecoder; - ArticleWriterImpl m_ArticleWriter; - ServerStatList m_ServerStats; - bool m_bWritingStarted; - int m_iDownloadedSize; + FileInfo* m_fileInfo; + ArticleInfo* m_articleInfo; + NNTPConnection* m_connection; + EStatus m_status; + Mutex m_connectionMutex; + char* m_infoName; + char m_connectionName[250]; + char* m_articleFilename; + time_t m_lastUpdateTime; + Decoder::EFormat m_format; + YDecoder m_yDecoder; + UDecoder m_uDecoder; + ArticleWriterImpl m_articleWriter; + ServerStatList m_serverStats; + bool m_writingStarted; + int m_downloadedSize; EStatus Download(); EStatus DecodeCheck(); - void FreeConnection(bool bKeepConnected); - EStatus CheckResponse(const char* szResponse, const char* szComment); - void SetStatus(EStatus eStatus) { m_eStatus = eStatus; } - bool Write(char* szLine, int iLen); + void FreeConnection(bool keepConnected); + EStatus CheckResponse(const char* response, const char* comment); + void SetStatus(EStatus status) { m_status = status; } + bool Write(char* line, int len); void AddServerData(); public: ArticleDownloader(); virtual ~ArticleDownloader(); - void SetFileInfo(FileInfo* pFileInfo) { m_pFileInfo = pFileInfo; } - FileInfo* GetFileInfo() { return m_pFileInfo; } - void SetArticleInfo(ArticleInfo* pArticleInfo) { m_pArticleInfo = pArticleInfo; } - ArticleInfo* GetArticleInfo() { return m_pArticleInfo; } - EStatus GetStatus() { return m_eStatus; } - ServerStatList* GetServerStats() { return &m_ServerStats; } + void SetFileInfo(FileInfo* fileInfo) { m_fileInfo = fileInfo; } + FileInfo* GetFileInfo() { return m_fileInfo; } + void SetArticleInfo(ArticleInfo* articleInfo) { m_articleInfo = articleInfo; } + ArticleInfo* GetArticleInfo() { return m_articleInfo; } + EStatus GetStatus() { return m_status; } + ServerStatList* GetServerStats() { return &m_serverStats; } virtual void Run(); virtual void Stop(); bool Terminate(); - time_t GetLastUpdateTime() { return m_tLastUpdateTime; } - void SetLastUpdateTimeNow() { m_tLastUpdateTime = ::time(NULL); } - const char* GetArticleFilename() { return m_szArticleFilename; } - void SetInfoName(const char* szInfoName); - const char* GetInfoName() { return m_szInfoName; } - const char* GetConnectionName() { return m_szConnectionName; } - void SetConnection(NNTPConnection* pConnection) { m_pConnection = pConnection; } - void CompleteFileParts() { m_ArticleWriter.CompleteFileParts(); } - int GetDownloadedSize() { return m_iDownloadedSize; } + time_t GetLastUpdateTime() { return m_lastUpdateTime; } + void SetLastUpdateTimeNow() { m_lastUpdateTime = ::time(NULL); } + const char* GetArticleFilename() { return m_articleFilename; } + void SetInfoName(const char* infoName); + const char* GetInfoName() { return m_infoName; } + const char* GetConnectionName() { return m_connectionName; } + void SetConnection(NNTPConnection* connection) { m_connection = connection; } + void CompleteFileParts() { m_articleWriter.CompleteFileParts(); } + int GetDownloadedSize() { return m_downloadedSize; } void LogDebugInfo(); }; diff --git a/daemon/nntp/ArticleWriter.cpp b/daemon/nntp/ArticleWriter.cpp index b17e453c..7a86a9b1 100644 --- a/daemon/nntp/ArticleWriter.cpp +++ b/daemon/nntp/ArticleWriter.cpp @@ -55,268 +55,268 @@ ArticleWriter::ArticleWriter() { debug("Creating ArticleWriter"); - m_szTempFilename = NULL; - m_szOutputFilename = NULL; - m_szResultFilename = NULL; - m_szInfoName = NULL; - m_eFormat = Decoder::efUnknown; - m_pArticleData = NULL; - m_bDuplicate = false; - m_bFlushing = false; + m_tempFilename = NULL; + m_outputFilename = NULL; + m_resultFilename = NULL; + m_infoName = NULL; + m_format = Decoder::efUnknown; + m_articleData = NULL; + m_duplicate = false; + m_flushing = false; } ArticleWriter::~ArticleWriter() { debug("Destroying ArticleWriter"); - free(m_szOutputFilename); - free(m_szTempFilename); - free(m_szInfoName); + free(m_outputFilename); + free(m_tempFilename); + free(m_infoName); - if (m_pArticleData) + if (m_articleData) { - free(m_pArticleData); - g_pArticleCache->Free(m_iArticleSize); + free(m_articleData); + g_pArticleCache->Free(m_articleSize); } - if (m_bFlushing) + if (m_flushing) { g_pArticleCache->UnlockFlush(); } } -void ArticleWriter::SetInfoName(const char* szInfoName) +void ArticleWriter::SetInfoName(const char* infoName) { - m_szInfoName = strdup(szInfoName); + m_infoName = strdup(infoName); } -void ArticleWriter::SetWriteBuffer(FILE* pOutFile, int iRecSize) +void ArticleWriter::SetWriteBuffer(FILE* outFile, int recSize) { if (g_pOptions->GetWriteBuffer() > 0) { - setvbuf(pOutFile, NULL, _IOFBF, - iRecSize > 0 && iRecSize < g_pOptions->GetWriteBuffer() * 1024 ? - iRecSize : g_pOptions->GetWriteBuffer() * 1024); + setvbuf(outFile, NULL, _IOFBF, + recSize > 0 && recSize < g_pOptions->GetWriteBuffer() * 1024 ? + recSize : g_pOptions->GetWriteBuffer() * 1024); } } void ArticleWriter::Prepare() { BuildOutputFilename(); - m_szResultFilename = m_pArticleInfo->GetResultFilename(); + m_resultFilename = m_articleInfo->GetResultFilename(); } -bool ArticleWriter::Start(Decoder::EFormat eFormat, const char* szFilename, long long iFileSize, - long long iArticleOffset, int iArticleSize) +bool ArticleWriter::Start(Decoder::EFormat format, const char* filename, long long fileSize, + long long articleOffset, int articleSize) { - char szErrBuf[256]; - m_pOutFile = NULL; - m_eFormat = eFormat; - m_iArticleOffset = iArticleOffset; - m_iArticleSize = iArticleSize ? iArticleSize : m_pArticleInfo->GetSize(); - m_iArticlePtr = 0; + char errBuf[256]; + m_outFile = NULL; + m_format = format; + m_articleOffset = articleOffset; + m_articleSize = articleSize ? articleSize : m_articleInfo->GetSize(); + m_articlePtr = 0; // prepare file for writing - if (m_eFormat == Decoder::efYenc) + if (m_format == Decoder::efYenc) { if (g_pOptions->GetDupeCheck() && - m_pFileInfo->GetNZBInfo()->GetDupeMode() != dmForce && - !m_pFileInfo->GetNZBInfo()->GetManyDupeFiles()) + m_fileInfo->GetNZBInfo()->GetDupeMode() != dmForce && + !m_fileInfo->GetNZBInfo()->GetManyDupeFiles()) { - m_pFileInfo->LockOutputFile(); - bool bOutputInitialized = m_pFileInfo->GetOutputInitialized(); + m_fileInfo->LockOutputFile(); + bool outputInitialized = m_fileInfo->GetOutputInitialized(); if (!g_pOptions->GetDirectWrite()) { - m_pFileInfo->SetOutputInitialized(true); + m_fileInfo->SetOutputInitialized(true); } - m_pFileInfo->UnlockOutputFile(); - if (!bOutputInitialized && szFilename && - Util::FileExists(m_pFileInfo->GetNZBInfo()->GetDestDir(), szFilename)) + m_fileInfo->UnlockOutputFile(); + if (!outputInitialized && filename && + Util::FileExists(m_fileInfo->GetNZBInfo()->GetDestDir(), filename)) { - m_bDuplicate = true; + m_duplicate = true; return false; } } if (g_pOptions->GetDirectWrite()) { - m_pFileInfo->LockOutputFile(); - if (!m_pFileInfo->GetOutputInitialized()) + m_fileInfo->LockOutputFile(); + if (!m_fileInfo->GetOutputInitialized()) { - if (!CreateOutputFile(iFileSize)) + if (!CreateOutputFile(fileSize)) { - m_pFileInfo->UnlockOutputFile(); + m_fileInfo->UnlockOutputFile(); return false; } - m_pFileInfo->SetOutputInitialized(true); + m_fileInfo->SetOutputInitialized(true); } - m_pFileInfo->UnlockOutputFile(); + m_fileInfo->UnlockOutputFile(); } } // allocate cache buffer if (g_pOptions->GetArticleCache() > 0 && g_pOptions->GetDecode() && - (!g_pOptions->GetDirectWrite() || m_eFormat == Decoder::efYenc)) + (!g_pOptions->GetDirectWrite() || m_format == Decoder::efYenc)) { - if (m_pArticleData) + if (m_articleData) { - free(m_pArticleData); - g_pArticleCache->Free(m_iArticleSize); + free(m_articleData); + g_pArticleCache->Free(m_articleSize); } - m_pArticleData = (char*)g_pArticleCache->Alloc(m_iArticleSize); + m_articleData = (char*)g_pArticleCache->Alloc(m_articleSize); - while (!m_pArticleData && g_pArticleCache->GetFlushing()) + while (!m_articleData && g_pArticleCache->GetFlushing()) { usleep(5 * 1000); - m_pArticleData = (char*)g_pArticleCache->Alloc(m_iArticleSize); + m_articleData = (char*)g_pArticleCache->Alloc(m_articleSize); } - if (!m_pArticleData) + if (!m_articleData) { - detail("Article cache is full, using disk for %s", m_szInfoName); + detail("Article cache is full, using disk for %s", m_infoName); } } - if (!m_pArticleData) + if (!m_articleData) { - bool bDirectWrite = g_pOptions->GetDirectWrite() && m_eFormat == Decoder::efYenc; - const char* szFilename = bDirectWrite ? m_szOutputFilename : m_szTempFilename; - m_pOutFile = fopen(szFilename, bDirectWrite ? FOPEN_RBP : FOPEN_WB); - if (!m_pOutFile) + bool directWrite = g_pOptions->GetDirectWrite() && m_format == Decoder::efYenc; + const char* filename = directWrite ? m_outputFilename : m_tempFilename; + m_outFile = fopen(filename, directWrite ? FOPEN_RBP : FOPEN_WB); + if (!m_outFile) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not %s file %s: %s", bDirectWrite ? "open" : "create", szFilename, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not %s file %s: %s", directWrite ? "open" : "create", filename, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); return false; } - SetWriteBuffer(m_pOutFile, m_pArticleInfo->GetSize()); + SetWriteBuffer(m_outFile, m_articleInfo->GetSize()); - if (g_pOptions->GetDirectWrite() && m_eFormat == Decoder::efYenc) + if (g_pOptions->GetDirectWrite() && m_format == Decoder::efYenc) { - fseek(m_pOutFile, m_iArticleOffset, SEEK_SET); + fseek(m_outFile, m_articleOffset, SEEK_SET); } } return true; } -bool ArticleWriter::Write(char* szBufffer, int iLen) +bool ArticleWriter::Write(char* bufffer, int len) { if (g_pOptions->GetDecode()) { - m_iArticlePtr += iLen; + m_articlePtr += len; } - if (g_pOptions->GetDecode() && m_pArticleData) + if (g_pOptions->GetDecode() && m_articleData) { - if (m_iArticlePtr > m_iArticleSize) + if (m_articlePtr > m_articleSize) { - detail("Decoding %s failed: article size mismatch", m_szInfoName); + detail("Decoding %s failed: article size mismatch", m_infoName); return false; } - memcpy(m_pArticleData + m_iArticlePtr - iLen, szBufffer, iLen); + memcpy(m_articleData + m_articlePtr - len, bufffer, len); return true; } - return fwrite(szBufffer, 1, iLen, m_pOutFile) > 0; + return fwrite(bufffer, 1, len, m_outFile) > 0; } -void ArticleWriter::Finish(bool bSuccess) +void ArticleWriter::Finish(bool success) { - char szErrBuf[256]; + char errBuf[256]; - if (m_pOutFile) + if (m_outFile) { - fclose(m_pOutFile); - m_pOutFile = NULL; + fclose(m_outFile); + m_outFile = NULL; } - if (!bSuccess) + if (!success) { - remove(m_szTempFilename); - remove(m_szResultFilename); + remove(m_tempFilename); + remove(m_resultFilename); return; } - bool bDirectWrite = g_pOptions->GetDirectWrite() && m_eFormat == Decoder::efYenc; + bool directWrite = g_pOptions->GetDirectWrite() && m_format == Decoder::efYenc; if (g_pOptions->GetDecode()) { - if (!bDirectWrite && !m_pArticleData) + if (!directWrite && !m_articleData) { - if (!Util::MoveFile(m_szTempFilename, m_szResultFilename)) + if (!Util::MoveFile(m_tempFilename, m_resultFilename)) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not rename file %s to %s: %s", m_szTempFilename, m_szResultFilename, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not rename file %s to %s: %s", m_tempFilename, m_resultFilename, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } - remove(m_szTempFilename); + remove(m_tempFilename); - if (m_pArticleData) + if (m_articleData) { - if (m_iArticleSize != m_iArticlePtr) + if (m_articleSize != m_articlePtr) { - m_pArticleData = (char*)g_pArticleCache->Realloc(m_pArticleData, m_iArticleSize, m_iArticlePtr); + m_articleData = (char*)g_pArticleCache->Realloc(m_articleData, m_articleSize, m_articlePtr); } g_pArticleCache->LockContent(); - m_pArticleInfo->AttachSegment(m_pArticleData, m_iArticleOffset, m_iArticlePtr); - m_pFileInfo->SetCachedArticles(m_pFileInfo->GetCachedArticles() + 1); + m_articleInfo->AttachSegment(m_articleData, m_articleOffset, m_articlePtr); + m_fileInfo->SetCachedArticles(m_fileInfo->GetCachedArticles() + 1); g_pArticleCache->UnlockContent(); - m_pArticleData = NULL; + m_articleData = NULL; } else { - m_pArticleInfo->SetSegmentOffset(m_iArticleOffset); - m_pArticleInfo->SetSegmentSize(m_iArticlePtr); + m_articleInfo->SetSegmentOffset(m_articleOffset); + m_articleInfo->SetSegmentSize(m_articlePtr); } } else { // rawmode - if (!Util::MoveFile(m_szTempFilename, m_szResultFilename)) + if (!Util::MoveFile(m_tempFilename, m_resultFilename)) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not move file %s to %s: %s", m_szTempFilename, m_szResultFilename, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not move file %s to %s: %s", m_tempFilename, m_resultFilename, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } } /* creates output file and subdirectores */ -bool ArticleWriter::CreateOutputFile(long long iSize) +bool ArticleWriter::CreateOutputFile(long long size) { - if (g_pOptions->GetDirectWrite() && Util::FileExists(m_szOutputFilename) && - Util::FileSize(m_szOutputFilename) == iSize) + if (g_pOptions->GetDirectWrite() && Util::FileExists(m_outputFilename) && + Util::FileSize(m_outputFilename) == size) { // keep existing old file from previous program session return true; } // delete eventually existing old file from previous program session - remove(m_szOutputFilename); + remove(m_outputFilename); // ensure the directory exist - char szDestDir[1024]; - int iMaxlen = Util::BaseFileName(m_szOutputFilename) - m_szOutputFilename; - if (iMaxlen > 1024-1) iMaxlen = 1024-1; - strncpy(szDestDir, m_szOutputFilename, iMaxlen); - szDestDir[iMaxlen] = '\0'; - char szErrBuf[1024]; + char destDir[1024]; + int maxlen = Util::BaseFileName(m_outputFilename) - m_outputFilename; + if (maxlen > 1024-1) maxlen = 1024-1; + strncpy(destDir, m_outputFilename, maxlen); + destDir[maxlen] = '\0'; + char errBuf[1024]; - if (!Util::ForceDirectories(szDestDir, szErrBuf, sizeof(szErrBuf))) + if (!Util::ForceDirectories(destDir, errBuf, sizeof(errBuf))) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not create directory %s: %s", szDestDir, szErrBuf); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not create directory %s: %s", destDir, errBuf); return false; } - if (!Util::CreateSparseFile(m_szOutputFilename, iSize, szErrBuf, sizeof(szErrBuf))) + if (!Util::CreateSparseFile(m_outputFilename, size, errBuf, sizeof(errBuf))) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not create file %s: %s", m_szOutputFilename, szErrBuf); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not create file %s: %s", m_outputFilename, errBuf); return false; } @@ -325,117 +325,117 @@ bool ArticleWriter::CreateOutputFile(long long iSize) void ArticleWriter::BuildOutputFilename() { - char szFilename[1024]; + char filename[1024]; - snprintf(szFilename, 1024, "%s%i.%03i", g_pOptions->GetTempDir(), m_pFileInfo->GetID(), m_pArticleInfo->GetPartNumber()); - szFilename[1024-1] = '\0'; - m_pArticleInfo->SetResultFilename(szFilename); + snprintf(filename, 1024, "%s%i.%03i", g_pOptions->GetTempDir(), m_fileInfo->GetID(), m_articleInfo->GetPartNumber()); + filename[1024-1] = '\0'; + m_articleInfo->SetResultFilename(filename); char tmpname[1024]; - snprintf(tmpname, 1024, "%s.tmp", szFilename); + snprintf(tmpname, 1024, "%s.tmp", filename); tmpname[1024-1] = '\0'; - m_szTempFilename = strdup(tmpname); + m_tempFilename = strdup(tmpname); if (g_pOptions->GetDirectWrite()) { - m_pFileInfo->LockOutputFile(); + m_fileInfo->LockOutputFile(); - if (m_pFileInfo->GetOutputFilename()) + if (m_fileInfo->GetOutputFilename()) { - strncpy(szFilename, m_pFileInfo->GetOutputFilename(), 1024); - szFilename[1024-1] = '\0'; + strncpy(filename, m_fileInfo->GetOutputFilename(), 1024); + filename[1024-1] = '\0'; } else { - snprintf(szFilename, 1024, "%s%c%i.out.tmp", m_pFileInfo->GetNZBInfo()->GetDestDir(), (int)PATH_SEPARATOR, m_pFileInfo->GetID()); - szFilename[1024-1] = '\0'; - m_pFileInfo->SetOutputFilename(szFilename); + snprintf(filename, 1024, "%s%c%i.out.tmp", m_fileInfo->GetNZBInfo()->GetDestDir(), (int)PATH_SEPARATOR, m_fileInfo->GetID()); + filename[1024-1] = '\0'; + m_fileInfo->SetOutputFilename(filename); } - m_pFileInfo->UnlockOutputFile(); + m_fileInfo->UnlockOutputFile(); - m_szOutputFilename = strdup(szFilename); + m_outputFilename = strdup(filename); } } void ArticleWriter::CompleteFileParts() { debug("Completing file parts"); - debug("ArticleFilename: %s", m_pFileInfo->GetFilename()); + debug("ArticleFilename: %s", m_fileInfo->GetFilename()); - bool bDirectWrite = g_pOptions->GetDirectWrite() && m_pFileInfo->GetOutputInitialized(); - char szErrBuf[256]; + bool directWrite = g_pOptions->GetDirectWrite() && m_fileInfo->GetOutputInitialized(); + char errBuf[256]; - char szNZBName[1024]; - char szNZBDestDir[1024]; + char nzbName[1024]; + char nzbDestDir[1024]; // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); - strncpy(szNZBName, m_pFileInfo->GetNZBInfo()->GetName(), 1024); - strncpy(szNZBDestDir, m_pFileInfo->GetNZBInfo()->GetDestDir(), 1024); + strncpy(nzbName, m_fileInfo->GetNZBInfo()->GetName(), 1024); + strncpy(nzbDestDir, m_fileInfo->GetNZBInfo()->GetDestDir(), 1024); DownloadQueue::Unlock(); - szNZBName[1024-1] = '\0'; - szNZBDestDir[1024-1] = '\0'; + nzbName[1024-1] = '\0'; + nzbDestDir[1024-1] = '\0'; - char szInfoFilename[1024]; - snprintf(szInfoFilename, 1024, "%s%c%s", szNZBName, (int)PATH_SEPARATOR, m_pFileInfo->GetFilename()); - szInfoFilename[1024-1] = '\0'; + char infoFilename[1024]; + snprintf(infoFilename, 1024, "%s%c%s", nzbName, (int)PATH_SEPARATOR, m_fileInfo->GetFilename()); + infoFilename[1024-1] = '\0'; - bool bCached = m_pFileInfo->GetCachedArticles() > 0; + bool cached = m_fileInfo->GetCachedArticles() > 0; if (!g_pOptions->GetDecode()) { - detail("Moving articles for %s", szInfoFilename); + detail("Moving articles for %s", infoFilename); } - else if (bDirectWrite && bCached) + else if (directWrite && cached) { - detail("Writing articles for %s", szInfoFilename); + detail("Writing articles for %s", infoFilename); } - else if (bDirectWrite) + else if (directWrite) { - detail("Checking articles for %s", szInfoFilename); + detail("Checking articles for %s", infoFilename); } else { - detail("Joining articles for %s", szInfoFilename); + detail("Joining articles for %s", infoFilename); } // Ensure the DstDir is created - if (!Util::ForceDirectories(szNZBDestDir, szErrBuf, sizeof(szErrBuf))) + if (!Util::ForceDirectories(nzbDestDir, errBuf, sizeof(errBuf))) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not create directory %s: %s", szNZBDestDir, szErrBuf); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not create directory %s: %s", nzbDestDir, errBuf); return; } char ofn[1024]; - Util::MakeUniqueFilename(ofn, 1024, szNZBDestDir, m_pFileInfo->GetFilename()); + Util::MakeUniqueFilename(ofn, 1024, nzbDestDir, m_fileInfo->GetFilename()); FILE* outfile = NULL; char tmpdestfile[1024]; snprintf(tmpdestfile, 1024, "%s.tmp", ofn); tmpdestfile[1024-1] = '\0'; - if (g_pOptions->GetDecode() && !bDirectWrite) + if (g_pOptions->GetDecode() && !directWrite) { remove(tmpdestfile); outfile = fopen(tmpdestfile, FOPEN_WBP); if (!outfile) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not create file %s: %s", tmpdestfile, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not create file %s: %s", tmpdestfile, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); return; } } - else if (bDirectWrite && bCached) + else if (directWrite && cached) { - outfile = fopen(m_szOutputFilename, FOPEN_RBP); + outfile = fopen(m_outputFilename, FOPEN_RBP); if (!outfile) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not open file %s: %s", m_szOutputFilename, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not open file %s: %s", m_outputFilename, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); return; } - strncpy(tmpdestfile, m_szOutputFilename, 1024); + strncpy(tmpdestfile, m_outputFilename, 1024); tmpdestfile[1024-1] = '\0'; } else if (!g_pOptions->GetDecode()) @@ -443,8 +443,8 @@ void ArticleWriter::CompleteFileParts() remove(tmpdestfile); if (!Util::CreateDirectory(ofn)) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not create directory %s: %s", ofn, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not create directory %s: %s", ofn, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); return; } } @@ -454,23 +454,23 @@ void ArticleWriter::CompleteFileParts() SetWriteBuffer(outfile, 0); } - if (bCached) + if (cached) { g_pArticleCache->LockFlush(); - m_bFlushing = true; + m_flushing = true; } static const int BUFFER_SIZE = 1024 * 64; char* buffer = NULL; - bool bFirstArticle = true; - unsigned long lCrc = 0; + bool firstArticle = true; + unsigned long crc = 0; - if (g_pOptions->GetDecode() && !bDirectWrite) + if (g_pOptions->GetDecode() && !directWrite) { buffer = (char*)malloc(BUFFER_SIZE); } - for (FileInfo::Articles::iterator it = m_pFileInfo->GetArticles()->begin(); it != m_pFileInfo->GetArticles()->end(); it++) + for (FileInfo::Articles::iterator it = m_fileInfo->GetArticles()->begin(); it != m_fileInfo->GetArticles()->end(); it++) { ArticleInfo* pa = *it; if (pa->GetStatus() != ArticleInfo::aiFinished) @@ -478,7 +478,7 @@ void ArticleWriter::CompleteFileParts() continue; } - if (g_pOptions->GetDecode() && !bDirectWrite && pa->GetSegmentOffset() > -1 && + if (g_pOptions->GetDecode() && !directWrite && pa->GetSegmentOffset() > -1 && pa->GetSegmentOffset() > ftell(outfile) && ftell(outfile) > -1) { memset(buffer, 0, BUFFER_SIZE); @@ -493,7 +493,7 @@ void ArticleWriter::CompleteFileParts() pa->DiscardSegment(); SetLastUpdateTimeNow(); } - else if (g_pOptions->GetDecode() && !bDirectWrite) + else if (g_pOptions->GetDecode() && !directWrite) { FILE* infile = pa->GetResultFilename() ? fopen(pa->GetResultFilename(), FOPEN_RB) : NULL; if (infile) @@ -509,12 +509,12 @@ void ArticleWriter::CompleteFileParts() } else { - m_pFileInfo->SetFailedArticles(m_pFileInfo->GetFailedArticles() + 1); - m_pFileInfo->SetSuccessArticles(m_pFileInfo->GetSuccessArticles() - 1); - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + m_fileInfo->SetFailedArticles(m_fileInfo->GetFailedArticles() + 1); + m_fileInfo->SetSuccessArticles(m_fileInfo->GetSuccessArticles() - 1); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, "Could not find file %s for %s%c%s [%i/%i]", - pa->GetResultFilename(), szNZBName, (int)PATH_SEPARATOR, m_pFileInfo->GetFilename(), - pa->GetPartNumber(), (int)m_pFileInfo->GetArticles()->size()); + pa->GetResultFilename(), nzbName, (int)PATH_SEPARATOR, m_fileInfo->GetFilename(), + pa->GetPartNumber(), (int)m_fileInfo->GetArticles()->size()); } } else if (!g_pOptions->GetDecode()) @@ -524,142 +524,142 @@ void ArticleWriter::CompleteFileParts() dstFileName[1024-1] = '\0'; if (!Util::MoveFile(pa->GetResultFilename(), dstFileName)) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, "Could not move file %s to %s: %s", pa->GetResultFilename(), dstFileName, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } - if (m_eFormat == Decoder::efYenc) + if (m_format == Decoder::efYenc) { - lCrc = bFirstArticle ? pa->GetCrc() : Util::Crc32Combine(lCrc, pa->GetCrc(), pa->GetSegmentSize()); - bFirstArticle = false; + crc = firstArticle ? pa->GetCrc() : Util::Crc32Combine(crc, pa->GetCrc(), pa->GetSegmentSize()); + firstArticle = false; } } free(buffer); - if (bCached) + if (cached) { g_pArticleCache->UnlockFlush(); - m_bFlushing = false; + m_flushing = false; } if (outfile) { fclose(outfile); - if (!bDirectWrite && !Util::MoveFile(tmpdestfile, ofn)) + if (!directWrite && !Util::MoveFile(tmpdestfile, ofn)) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, "Could not move file %s to %s: %s", tmpdestfile, ofn, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } - if (bDirectWrite) + if (directWrite) { - if (!Util::MoveFile(m_szOutputFilename, ofn)) + if (!Util::MoveFile(m_outputFilename, ofn)) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not move file %s to %s: %s", m_szOutputFilename, ofn, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not move file %s to %s: %s", m_outputFilename, ofn, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } // if destination directory was changed delete the old directory (if empty) - int iLen = strlen(szNZBDestDir); - if (!(!strncmp(szNZBDestDir, m_szOutputFilename, iLen) && - (m_szOutputFilename[iLen] == PATH_SEPARATOR || m_szOutputFilename[iLen] == ALT_PATH_SEPARATOR))) + int len = strlen(nzbDestDir); + if (!(!strncmp(nzbDestDir, m_outputFilename, len) && + (m_outputFilename[len] == PATH_SEPARATOR || m_outputFilename[len] == ALT_PATH_SEPARATOR))) { - debug("Checking old dir for: %s", m_szOutputFilename); - char szOldDestDir[1024]; - int iMaxlen = Util::BaseFileName(m_szOutputFilename) - m_szOutputFilename; - if (iMaxlen > 1024-1) iMaxlen = 1024-1; - strncpy(szOldDestDir, m_szOutputFilename, iMaxlen); - szOldDestDir[iMaxlen] = '\0'; - if (Util::DirEmpty(szOldDestDir)) + debug("Checking old dir for: %s", m_outputFilename); + char oldDestDir[1024]; + int maxlen = Util::BaseFileName(m_outputFilename) - m_outputFilename; + if (maxlen > 1024-1) maxlen = 1024-1; + strncpy(oldDestDir, m_outputFilename, maxlen); + oldDestDir[maxlen] = '\0'; + if (Util::DirEmpty(oldDestDir)) { - debug("Deleting old dir: %s", szOldDestDir); - rmdir(szOldDestDir); + debug("Deleting old dir: %s", oldDestDir); + rmdir(oldDestDir); } } } - if (!bDirectWrite) + if (!directWrite) { - for (FileInfo::Articles::iterator it = m_pFileInfo->GetArticles()->begin(); it != m_pFileInfo->GetArticles()->end(); it++) + for (FileInfo::Articles::iterator it = m_fileInfo->GetArticles()->begin(); it != m_fileInfo->GetArticles()->end(); it++) { ArticleInfo* pa = *it; remove(pa->GetResultFilename()); } } - if (m_pFileInfo->GetMissedArticles() == 0 && m_pFileInfo->GetFailedArticles() == 0) + if (m_fileInfo->GetMissedArticles() == 0 && m_fileInfo->GetFailedArticles() == 0) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, "Successfully downloaded %s", szInfoFilename); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, "Successfully downloaded %s", infoFilename); } else { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, "%i of %i article downloads failed for \"%s\"", - m_pFileInfo->GetMissedArticles() + m_pFileInfo->GetFailedArticles(), - m_pFileInfo->GetTotalArticles(), szInfoFilename); + m_fileInfo->GetMissedArticles() + m_fileInfo->GetFailedArticles(), + m_fileInfo->GetTotalArticles(), infoFilename); if (g_pOptions->GetBrokenLog()) { - char szBrokenLogName[1024]; - snprintf(szBrokenLogName, 1024, "%s%c_brokenlog.txt", szNZBDestDir, (int)PATH_SEPARATOR); - szBrokenLogName[1024-1] = '\0'; - FILE* file = fopen(szBrokenLogName, FOPEN_AB); - fprintf(file, "%s (%i/%i)%s", m_pFileInfo->GetFilename(), m_pFileInfo->GetSuccessArticles(), - m_pFileInfo->GetTotalArticles(), LINE_ENDING); + char brokenLogName[1024]; + snprintf(brokenLogName, 1024, "%s%c_brokenlog.txt", nzbDestDir, (int)PATH_SEPARATOR); + brokenLogName[1024-1] = '\0'; + FILE* file = fopen(brokenLogName, FOPEN_AB); + fprintf(file, "%s (%i/%i)%s", m_fileInfo->GetFilename(), m_fileInfo->GetSuccessArticles(), + m_fileInfo->GetTotalArticles(), LINE_ENDING); fclose(file); } - lCrc = 0; + crc = 0; if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) { - g_pDiskState->DiscardFile(m_pFileInfo, false, true, false); - g_pDiskState->SaveFileState(m_pFileInfo, true); + g_pDiskState->DiscardFile(m_fileInfo, false, true, false); + g_pDiskState->SaveFileState(m_fileInfo, true); } } - CompletedFile::EStatus eFileStatus = m_pFileInfo->GetMissedArticles() == 0 && - m_pFileInfo->GetFailedArticles() == 0 ? CompletedFile::cfSuccess : - m_pFileInfo->GetSuccessArticles() > 0 ? CompletedFile::cfPartial : + CompletedFile::EStatus fileStatus = m_fileInfo->GetMissedArticles() == 0 && + m_fileInfo->GetFailedArticles() == 0 ? CompletedFile::cfSuccess : + m_fileInfo->GetSuccessArticles() > 0 ? CompletedFile::cfPartial : CompletedFile::cfFailure; // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); - m_pFileInfo->GetNZBInfo()->GetCompletedFiles()->push_back(new CompletedFile( - m_pFileInfo->GetID(), Util::BaseFileName(ofn), eFileStatus, lCrc)); - if (strcmp(m_pFileInfo->GetNZBInfo()->GetDestDir(), szNZBDestDir)) + m_fileInfo->GetNZBInfo()->GetCompletedFiles()->push_back(new CompletedFile( + m_fileInfo->GetID(), Util::BaseFileName(ofn), fileStatus, crc)); + if (strcmp(m_fileInfo->GetNZBInfo()->GetDestDir(), nzbDestDir)) { // destination directory was changed during completion, need to move the file - MoveCompletedFiles(m_pFileInfo->GetNZBInfo(), szNZBDestDir); + MoveCompletedFiles(m_fileInfo->GetNZBInfo(), nzbDestDir); } DownloadQueue::Unlock(); } void ArticleWriter::FlushCache() { - detail("Flushing cache for %s", m_szInfoName); + detail("Flushing cache for %s", m_infoName); - bool bDirectWrite = g_pOptions->GetDirectWrite() && m_pFileInfo->GetOutputInitialized(); + bool directWrite = g_pOptions->GetDirectWrite() && m_fileInfo->GetOutputInitialized(); FILE* outfile = NULL; - bool bNeedBufFile = false; - char szDestFile[1024]; - char szErrBuf[256]; - int iFlushedArticles = 0; - long long iFlushedSize = 0; + bool needBufFile = false; + char destFile[1024]; + char errBuf[256]; + int flushedArticles = 0; + long long flushedSize = 0; g_pArticleCache->LockFlush(); FileInfo::Articles cachedArticles; - cachedArticles.reserve(m_pFileInfo->GetArticles()->size()); + cachedArticles.reserve(m_fileInfo->GetArticles()->size()); g_pArticleCache->LockContent(); - for (FileInfo::Articles::iterator it = m_pFileInfo->GetArticles()->begin(); it != m_pFileInfo->GetArticles()->end(); it++) + for (FileInfo::Articles::iterator it = m_fileInfo->GetArticles()->begin(); it != m_fileInfo->GetArticles()->end(); it++) { ArticleInfo* pa = *it; if (pa->GetSegmentContent()) @@ -671,7 +671,7 @@ void ArticleWriter::FlushCache() for (FileInfo::Articles::iterator it = cachedArticles.begin(); it != cachedArticles.end(); it++) { - if (m_pFileInfo->GetDeleted()) + if (m_fileInfo->GetDeleted()) { // the file was deleted during flushing: stop flushing immediately break; @@ -679,63 +679,63 @@ void ArticleWriter::FlushCache() ArticleInfo* pa = *it; - if (bDirectWrite && !outfile) + if (directWrite && !outfile) { - outfile = fopen(m_pFileInfo->GetOutputFilename(), FOPEN_RBP); + outfile = fopen(m_fileInfo->GetOutputFilename(), FOPEN_RBP); if (!outfile) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not open file %s: %s", m_pFileInfo->GetOutputFilename(), - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not open file %s: %s", m_fileInfo->GetOutputFilename(), + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); break; } - bNeedBufFile = true; + needBufFile = true; } - if (!bDirectWrite) + if (!directWrite) { - snprintf(szDestFile, 1024, "%s.tmp", pa->GetResultFilename()); - szDestFile[1024-1] = '\0'; + snprintf(destFile, 1024, "%s.tmp", pa->GetResultFilename()); + destFile[1024-1] = '\0'; - outfile = fopen(szDestFile, FOPEN_WB); + outfile = fopen(destFile, FOPEN_WB); if (!outfile) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not create file %s: %s", "create", szDestFile, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not create file %s: %s", "create", destFile, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); break; } - bNeedBufFile = true; + needBufFile = true; } - if (outfile && bNeedBufFile) + if (outfile && needBufFile) { SetWriteBuffer(outfile, 0); - bNeedBufFile = false; + needBufFile = false; } - if (bDirectWrite) + if (directWrite) { fseek(outfile, pa->GetSegmentOffset(), SEEK_SET); } fwrite(pa->GetSegmentContent(), 1, pa->GetSegmentSize(), outfile); - iFlushedSize += pa->GetSegmentSize(); - iFlushedArticles++; + flushedSize += pa->GetSegmentSize(); + flushedArticles++; pa->DiscardSegment(); - if (!bDirectWrite) + if (!directWrite) { fclose(outfile); outfile = NULL; - if (!Util::MoveFile(szDestFile, pa->GetResultFilename())) + if (!Util::MoveFile(destFile, pa->GetResultFilename())) { - m_pFileInfo->GetNZBInfo()->PrintMessage(Message::mkError, - "Could not rename file %s to %s: %s", szDestFile, pa->GetResultFilename(), - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + m_fileInfo->GetNZBInfo()->PrintMessage(Message::mkError, + "Could not rename file %s to %s: %s", destFile, pa->GetResultFilename(), + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } } @@ -746,54 +746,54 @@ void ArticleWriter::FlushCache() } g_pArticleCache->LockContent(); - m_pFileInfo->SetCachedArticles(m_pFileInfo->GetCachedArticles() - iFlushedArticles); + m_fileInfo->SetCachedArticles(m_fileInfo->GetCachedArticles() - flushedArticles); g_pArticleCache->UnlockContent(); g_pArticleCache->UnlockFlush(); - detail("Saved %i articles (%.2f MB) from cache into disk for %s", iFlushedArticles, (float)(iFlushedSize / 1024.0 / 1024.0), m_szInfoName); + detail("Saved %i articles (%.2f MB) from cache into disk for %s", flushedArticles, (float)(flushedSize / 1024.0 / 1024.0), m_infoName); } -bool ArticleWriter::MoveCompletedFiles(NZBInfo* pNZBInfo, const char* szOldDestDir) +bool ArticleWriter::MoveCompletedFiles(NZBInfo* nzbInfo, const char* oldDestDir) { - if (pNZBInfo->GetCompletedFiles()->empty()) + if (nzbInfo->GetCompletedFiles()->empty()) { return true; } // Ensure the DstDir is created - char szErrBuf[1024]; - if (!Util::ForceDirectories(pNZBInfo->GetDestDir(), szErrBuf, sizeof(szErrBuf))) + char errBuf[1024]; + if (!Util::ForceDirectories(nzbInfo->GetDestDir(), errBuf, sizeof(errBuf))) { - pNZBInfo->PrintMessage(Message::mkError, "Could not create directory %s: %s", pNZBInfo->GetDestDir(), szErrBuf); + nzbInfo->PrintMessage(Message::mkError, "Could not create directory %s: %s", nzbInfo->GetDestDir(), errBuf); return false; } // move already downloaded files to new destination - for (CompletedFiles::iterator it = pNZBInfo->GetCompletedFiles()->begin(); it != pNZBInfo->GetCompletedFiles()->end(); it++) + for (CompletedFiles::iterator it = nzbInfo->GetCompletedFiles()->begin(); it != nzbInfo->GetCompletedFiles()->end(); it++) { - CompletedFile* pCompletedFile = *it; + CompletedFile* completedFile = *it; - char szOldFileName[1024]; - snprintf(szOldFileName, 1024, "%s%c%s", szOldDestDir, (int)PATH_SEPARATOR, pCompletedFile->GetFileName()); - szOldFileName[1024-1] = '\0'; + char oldFileName[1024]; + snprintf(oldFileName, 1024, "%s%c%s", oldDestDir, (int)PATH_SEPARATOR, completedFile->GetFileName()); + oldFileName[1024-1] = '\0'; - char szNewFileName[1024]; - snprintf(szNewFileName, 1024, "%s%c%s", pNZBInfo->GetDestDir(), (int)PATH_SEPARATOR, pCompletedFile->GetFileName()); - szNewFileName[1024-1] = '\0'; + char newFileName[1024]; + snprintf(newFileName, 1024, "%s%c%s", nzbInfo->GetDestDir(), (int)PATH_SEPARATOR, completedFile->GetFileName()); + newFileName[1024-1] = '\0'; // check if file was not moved already - if (strcmp(szOldFileName, szNewFileName)) + if (strcmp(oldFileName, newFileName)) { // prevent overwriting of existing files - Util::MakeUniqueFilename(szNewFileName, 1024, pNZBInfo->GetDestDir(), pCompletedFile->GetFileName()); + Util::MakeUniqueFilename(newFileName, 1024, nzbInfo->GetDestDir(), completedFile->GetFileName()); - detail("Moving file %s to %s", szOldFileName, szNewFileName); - if (!Util::MoveFile(szOldFileName, szNewFileName)) + detail("Moving file %s to %s", oldFileName, newFileName); + if (!Util::MoveFile(oldFileName, newFileName)) { - char szErrBuf[256]; - pNZBInfo->PrintMessage(Message::mkError, "Could not move file %s to %s: %s", - szOldFileName, szNewFileName, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + char errBuf[256]; + nzbInfo->PrintMessage(Message::mkError, "Could not move file %s to %s: %s", + oldFileName, newFileName, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } } @@ -801,25 +801,25 @@ bool ArticleWriter::MoveCompletedFiles(NZBInfo* pNZBInfo, const char* szOldDestD // move brokenlog.txt if (g_pOptions->GetBrokenLog()) { - char szOldBrokenLogName[1024]; - snprintf(szOldBrokenLogName, 1024, "%s%c_brokenlog.txt", szOldDestDir, (int)PATH_SEPARATOR); - szOldBrokenLogName[1024-1] = '\0'; - if (Util::FileExists(szOldBrokenLogName)) + char oldBrokenLogName[1024]; + snprintf(oldBrokenLogName, 1024, "%s%c_brokenlog.txt", oldDestDir, (int)PATH_SEPARATOR); + oldBrokenLogName[1024-1] = '\0'; + if (Util::FileExists(oldBrokenLogName)) { - char szBrokenLogName[1024]; - snprintf(szBrokenLogName, 1024, "%s%c_brokenlog.txt", pNZBInfo->GetDestDir(), (int)PATH_SEPARATOR); - szBrokenLogName[1024-1] = '\0'; + char brokenLogName[1024]; + snprintf(brokenLogName, 1024, "%s%c_brokenlog.txt", nzbInfo->GetDestDir(), (int)PATH_SEPARATOR); + brokenLogName[1024-1] = '\0'; - detail("Moving file %s to %s", szOldBrokenLogName, szBrokenLogName); - if (Util::FileExists(szBrokenLogName)) + detail("Moving file %s to %s", oldBrokenLogName, brokenLogName); + if (Util::FileExists(brokenLogName)) { // copy content to existing new file, then delete old file FILE* outfile; - outfile = fopen(szBrokenLogName, FOPEN_AB); + outfile = fopen(brokenLogName, FOPEN_AB); if (outfile) { FILE* infile; - infile = fopen(szOldBrokenLogName, FOPEN_RB); + infile = fopen(oldBrokenLogName, FOPEN_RB); if (infile) { static const int BUFFER_SIZE = 1024 * 50; @@ -832,55 +832,55 @@ bool ArticleWriter::MoveCompletedFiles(NZBInfo* pNZBInfo, const char* szOldDestD } fclose(infile); free(buffer); - remove(szOldBrokenLogName); + remove(oldBrokenLogName); } else { - pNZBInfo->PrintMessage(Message::mkError, "Could not open file %s", szOldBrokenLogName); + nzbInfo->PrintMessage(Message::mkError, "Could not open file %s", oldBrokenLogName); } fclose(outfile); } else { - pNZBInfo->PrintMessage(Message::mkError, "Could not open file %s", szBrokenLogName); + nzbInfo->PrintMessage(Message::mkError, "Could not open file %s", brokenLogName); } } else { // move to new destination - if (!Util::MoveFile(szOldBrokenLogName, szBrokenLogName)) + if (!Util::MoveFile(oldBrokenLogName, brokenLogName)) { - char szErrBuf[256]; - pNZBInfo->PrintMessage(Message::mkError, "Could not move file %s to %s: %s", - szOldBrokenLogName, szBrokenLogName, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + char errBuf[256]; + nzbInfo->PrintMessage(Message::mkError, "Could not move file %s to %s: %s", + oldBrokenLogName, brokenLogName, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } } } // delete old directory (if empty) - if (Util::DirEmpty(szOldDestDir)) + if (Util::DirEmpty(oldDestDir)) { // check if there are pending writes into directory - bool bPendingWrites = false; - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end() && !bPendingWrites; it++) + bool pendingWrites = false; + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end() && !pendingWrites; it++) { - FileInfo* pFileInfo = *it; - if (pFileInfo->GetActiveDownloads() > 0) + FileInfo* fileInfo = *it; + if (fileInfo->GetActiveDownloads() > 0) { - pFileInfo->LockOutputFile(); - bPendingWrites = pFileInfo->GetOutputInitialized() && !Util::EmptyStr(pFileInfo->GetOutputFilename()); - pFileInfo->UnlockOutputFile(); + fileInfo->LockOutputFile(); + pendingWrites = fileInfo->GetOutputInitialized() && !Util::EmptyStr(fileInfo->GetOutputFilename()); + fileInfo->UnlockOutputFile(); } else { - bPendingWrites = pFileInfo->GetOutputInitialized() && !Util::EmptyStr(pFileInfo->GetOutputFilename()); + pendingWrites = fileInfo->GetOutputInitialized() && !Util::EmptyStr(fileInfo->GetOutputFilename()); } } - if (!bPendingWrites) + if (!pendingWrites) { - rmdir(szOldDestDir); + rmdir(oldDestDir); } } @@ -890,130 +890,130 @@ bool ArticleWriter::MoveCompletedFiles(NZBInfo* pNZBInfo, const char* szOldDestD ArticleCache::ArticleCache() { - m_iAllocated = 0; - m_bFlushing = false; - m_pFileInfo = NULL; + m_allocated = 0; + m_flushing = false; + m_fileInfo = NULL; } -void* ArticleCache::Alloc(int iSize) +void* ArticleCache::Alloc(int size) { - m_mutexAlloc.Lock(); + m_allocMutex.Lock(); void* p = NULL; - if (m_iAllocated + iSize <= (size_t)g_pOptions->GetArticleCache() * 1024 * 1024) + if (m_allocated + size <= (size_t)g_pOptions->GetArticleCache() * 1024 * 1024) { - p = malloc(iSize); + p = malloc(size); if (p) { - if (!m_iAllocated && g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode() && g_pOptions->GetContinuePartial()) + if (!m_allocated && g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode() && g_pOptions->GetContinuePartial()) { g_pDiskState->WriteCacheFlag(); } - m_iAllocated += iSize; + m_allocated += size; } } - m_mutexAlloc.Unlock(); + m_allocMutex.Unlock(); return p; } -void* ArticleCache::Realloc(void* buf, int iOldSize, int iNewSize) +void* ArticleCache::Realloc(void* buf, int oldSize, int newSize) { - m_mutexAlloc.Lock(); + m_allocMutex.Lock(); - void* p = realloc(buf, iNewSize); + void* p = realloc(buf, newSize); if (p) { - m_iAllocated += iNewSize - iOldSize; + m_allocated += newSize - oldSize; } else { p = buf; } - m_mutexAlloc.Unlock(); + m_allocMutex.Unlock(); return p; } -void ArticleCache::Free(int iSize) +void ArticleCache::Free(int size) { - m_mutexAlloc.Lock(); - m_iAllocated -= iSize; - if (!m_iAllocated && g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode() && g_pOptions->GetContinuePartial()) + m_allocMutex.Lock(); + m_allocated -= size; + if (!m_allocated && g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode() && g_pOptions->GetContinuePartial()) { g_pDiskState->DeleteCacheFlag(); } - m_mutexAlloc.Unlock(); + m_allocMutex.Unlock(); } void ArticleCache::LockFlush() { - m_mutexFlush.Lock(); - m_bFlushing = true; + m_flushMutex.Lock(); + m_flushing = true; } void ArticleCache::UnlockFlush() { - m_mutexFlush.Unlock(); - m_bFlushing = false; + m_flushMutex.Unlock(); + m_flushing = false; } void ArticleCache::Run() { // automatically flush the cache if it is filled to 90% (only in DirectWrite mode) - size_t iFillThreshold = (size_t)g_pOptions->GetArticleCache() * 1024 * 1024 / 100 * 90; + size_t fillThreshold = (size_t)g_pOptions->GetArticleCache() * 1024 * 1024 / 100 * 90; - int iResetCounter = 0; - bool bJustFlushed = false; - while (!IsStopped() || m_iAllocated > 0) + int resetCounter = 0; + bool justFlushed = false; + while (!IsStopped() || m_allocated > 0) { - if ((bJustFlushed || iResetCounter >= 1000 || IsStopped() || - (g_pOptions->GetDirectWrite() && m_iAllocated >= iFillThreshold)) && - m_iAllocated > 0) + if ((justFlushed || resetCounter >= 1000 || IsStopped() || + (g_pOptions->GetDirectWrite() && m_allocated >= fillThreshold)) && + m_allocated > 0) { - bJustFlushed = CheckFlush(m_iAllocated >= iFillThreshold); - iResetCounter = 0; + justFlushed = CheckFlush(m_allocated >= fillThreshold); + resetCounter = 0; } else { usleep(5 * 1000); - iResetCounter += 5; + resetCounter += 5; } } } -bool ArticleCache::CheckFlush(bool bFlushEverything) +bool ArticleCache::CheckFlush(bool flushEverything) { - debug("Checking cache, Allocated: %i, FlushEverything: %i", m_iAllocated, (int)bFlushEverything); + debug("Checking cache, Allocated: %i, FlushEverything: %i", m_allocated, (int)flushEverything); - char szInfoName[1024]; + char infoName[1024]; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end() && !m_pFileInfo; it++) + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end() && !m_fileInfo; it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - if (pFileInfo->GetCachedArticles() > 0 && (pFileInfo->GetActiveDownloads() == 0 || bFlushEverything)) + FileInfo* fileInfo = *it2; + if (fileInfo->GetCachedArticles() > 0 && (fileInfo->GetActiveDownloads() == 0 || flushEverything)) { - m_pFileInfo = pFileInfo; - snprintf(szInfoName, 1024, "%s%c%s", m_pFileInfo->GetNZBInfo()->GetName(), (int)PATH_SEPARATOR, m_pFileInfo->GetFilename()); - szInfoName[1024-1] = '\0'; + m_fileInfo = fileInfo; + snprintf(infoName, 1024, "%s%c%s", m_fileInfo->GetNZBInfo()->GetName(), (int)PATH_SEPARATOR, m_fileInfo->GetFilename()); + infoName[1024-1] = '\0'; break; } } } DownloadQueue::Unlock(); - if (m_pFileInfo) + if (m_fileInfo) { - ArticleWriter* pArticleWriter = new ArticleWriter(); - pArticleWriter->SetFileInfo(m_pFileInfo); - pArticleWriter->SetInfoName(szInfoName); - pArticleWriter->FlushCache(); - delete pArticleWriter; - m_pFileInfo = NULL; + ArticleWriter* articleWriter = new ArticleWriter(); + articleWriter->SetFileInfo(m_fileInfo); + articleWriter->SetInfoName(infoName); + articleWriter->FlushCache(); + delete articleWriter; + m_fileInfo = NULL; return true; } diff --git a/daemon/nntp/ArticleWriter.h b/daemon/nntp/ArticleWriter.h index e512a486..a4f00964 100644 --- a/daemon/nntp/ArticleWriter.h +++ b/daemon/nntp/ArticleWriter.h @@ -32,26 +32,26 @@ class ArticleWriter { private: - FileInfo* m_pFileInfo; - ArticleInfo* m_pArticleInfo; - FILE* m_pOutFile; - char* m_szTempFilename; - char* m_szOutputFilename; - const char* m_szResultFilename; - Decoder::EFormat m_eFormat; - char* m_pArticleData; - long long m_iArticleOffset; - int m_iArticleSize; - int m_iArticlePtr; - bool m_bFlushing; - bool m_bDuplicate; - char* m_szInfoName; + FileInfo* m_fileInfo; + ArticleInfo* m_articleInfo; + FILE* m_outFile; + char* m_tempFilename; + char* m_outputFilename; + const char* m_resultFilename; + Decoder::EFormat m_format; + char* m_articleData; + long long m_articleOffset; + int m_articleSize; + int m_articlePtr; + bool m_flushing; + bool m_duplicate; + char* m_infoName; - bool PrepareFile(char* szLine); - bool CreateOutputFile(long long iSize); + bool PrepareFile(char* line); + bool CreateOutputFile(long long size); void BuildOutputFilename(); bool IsFileCached(); - void SetWriteBuffer(FILE* pOutFile, int iRecSize); + void SetWriteBuffer(FILE* outFile, int recSize); protected: virtual void SetLastUpdateTimeNow() {} @@ -59,44 +59,44 @@ protected: public: ArticleWriter(); ~ArticleWriter(); - void SetInfoName(const char* szInfoName); - void SetFileInfo(FileInfo* pFileInfo) { m_pFileInfo = pFileInfo; } - void SetArticleInfo(ArticleInfo* pArticleInfo) { m_pArticleInfo = pArticleInfo; } + void SetInfoName(const char* infoName); + void SetFileInfo(FileInfo* fileInfo) { m_fileInfo = fileInfo; } + void SetArticleInfo(ArticleInfo* articleInfo) { m_articleInfo = articleInfo; } void Prepare(); - bool Start(Decoder::EFormat eFormat, const char* szFilename, long long iFileSize, long long iArticleOffset, int iArticleSize); - bool Write(char* szBufffer, int iLen); - void Finish(bool bSuccess); - bool GetDuplicate() { return m_bDuplicate; } + bool Start(Decoder::EFormat format, const char* filename, long long fileSize, long long articleOffset, int articleSize); + bool Write(char* bufffer, int len); + void Finish(bool success); + bool GetDuplicate() { return m_duplicate; } void CompleteFileParts(); - static bool MoveCompletedFiles(NZBInfo* pNZBInfo, const char* szOldDestDir); + static bool MoveCompletedFiles(NZBInfo* nzbInfo, const char* oldDestDir); void FlushCache(); }; class ArticleCache : public Thread { private: - size_t m_iAllocated; - bool m_bFlushing; - Mutex m_mutexAlloc; - Mutex m_mutexFlush; - Mutex m_mutexContent; - FileInfo* m_pFileInfo; + size_t m_allocated; + bool m_flushing; + Mutex m_allocMutex; + Mutex m_flushMutex; + Mutex m_contentMutex; + FileInfo* m_fileInfo; - bool CheckFlush(bool bFlushEverything); + bool CheckFlush(bool flushEverything); public: ArticleCache(); virtual void Run(); - void* Alloc(int iSize); - void* Realloc(void* buf, int iOldSize, int iNewSize); - void Free(int iSize); + void* Alloc(int size); + void* Realloc(void* buf, int oldSize, int newSize); + void Free(int size); void LockFlush(); void UnlockFlush(); - void LockContent() { m_mutexContent.Lock(); } - void UnlockContent() { m_mutexContent.Unlock(); } - bool GetFlushing() { return m_bFlushing; } - size_t GetAllocated() { return m_iAllocated; } - bool FileBusy(FileInfo* pFileInfo) { return pFileInfo == m_pFileInfo; } + void LockContent() { m_contentMutex.Lock(); } + void UnlockContent() { m_contentMutex.Unlock(); } + bool GetFlushing() { return m_flushing; } + size_t GetAllocated() { return m_allocated; } + bool FileBusy(FileInfo* fileInfo) { return fileInfo == m_fileInfo; } }; extern ArticleCache* g_pArticleCache; diff --git a/daemon/nntp/Decoder.cpp b/daemon/nntp/Decoder.cpp index 95406a37..d367b89f 100644 --- a/daemon/nntp/Decoder.cpp +++ b/daemon/nntp/Decoder.cpp @@ -49,20 +49,20 @@ Decoder::Decoder() { debug("Creating Decoder"); - m_szArticleFilename = NULL; + m_articleFilename = NULL; } Decoder::~ Decoder() { debug("Destroying Decoder"); - free(m_szArticleFilename); + free(m_articleFilename); } void Decoder::Clear() { - free(m_szArticleFilename); - m_szArticleFilename = NULL; + free(m_articleFilename); + m_articleFilename = NULL; } Decoder::EFormat Decoder::DetectFormat(const char* buffer, int len) @@ -79,18 +79,18 @@ Decoder::EFormat Decoder::DetectFormat(const char* buffer, int len) if (!strncmp(buffer, "begin ", 6)) { - bool bOK = true; + bool ok = true; buffer += 6; //strlen("begin ") while (*buffer && *buffer != ' ') { char ch = *buffer++; if (ch < '0' || ch > '7') { - bOK = false; + ok = false; break; } } - if (bOK) + if (ok) { return efUx; } @@ -112,39 +112,39 @@ void YDecoder::Clear() { Decoder::Clear(); - m_bBody = false; - m_bBegin = false; - m_bPart = false; - m_bEnd = false; - m_bCrc = false; - m_lExpectedCRC = 0; - m_lCalculatedCRC = 0xFFFFFFFF; - m_iBegin = 0; - m_iEnd = 0; - m_iSize = 0; - m_iEndSize = 0; - m_bCrcCheck = false; + m_body = false; + m_begin = false; + m_part = false; + m_end = false; + m_crc = false; + m_expectedCRC = 0; + m_calculatedCRC = 0xFFFFFFFF; + m_beginPos = 0; + m_endPos = 0; + m_size = 0; + m_endSize = 0; + m_crcCheck = false; } int YDecoder::DecodeBuffer(char* buffer, int len) { - if (m_bBody && !m_bEnd) + if (m_body && !m_end) { if (!strncmp(buffer, "=yend ", 6)) { - m_bEnd = true; - char* pb = strstr(buffer, m_bPart ? " pcrc32=" : " crc32="); + m_end = true; + char* pb = strstr(buffer, m_part ? " pcrc32=" : " crc32="); if (pb) { - m_bCrc = true; - pb += 7 + (int)m_bPart; //=strlen(" crc32=") or strlen(" pcrc32=") - m_lExpectedCRC = strtoul(pb, NULL, 16); + m_crc = true; + pb += 7 + (int)m_part; //=strlen(" crc32=") or strlen(" pcrc32=") + m_expectedCRC = strtoul(pb, NULL, 16); } pb = strstr(buffer, " size="); if (pb) { pb += 6; //=strlen(" size=") - m_iEndSize = (long long)atoll(pb); + m_endSize = (long long)atoll(pb); } return 0; } @@ -174,57 +174,57 @@ int YDecoder::DecodeBuffer(char* buffer, int len) } BreakLoop: - if (m_bCrcCheck) + if (m_crcCheck) { - m_lCalculatedCRC = Util::Crc32m(m_lCalculatedCRC, (unsigned char *)buffer, (unsigned int)(optr - buffer)); + m_calculatedCRC = Util::Crc32m(m_calculatedCRC, (unsigned char *)buffer, (unsigned int)(optr - buffer)); } return optr - buffer; } else { - if (!m_bPart && !strncmp(buffer, "=ybegin ", 8)) + if (!m_part && !strncmp(buffer, "=ybegin ", 8)) { - m_bBegin = true; + m_begin = true; char* pb = strstr(buffer, " name="); if (pb) { pb += 6; //=strlen(" name=") char* pe; for (pe = pb; *pe != '\0' && *pe != '\n' && *pe != '\r'; pe++) ; - free(m_szArticleFilename); - m_szArticleFilename = (char*)malloc(pe - pb + 1); - strncpy(m_szArticleFilename, pb, pe - pb); - m_szArticleFilename[pe - pb] = '\0'; + free(m_articleFilename); + m_articleFilename = (char*)malloc(pe - pb + 1); + strncpy(m_articleFilename, pb, pe - pb); + m_articleFilename[pe - pb] = '\0'; } pb = strstr(buffer, " size="); if (pb) { pb += 6; //=strlen(" size=") - m_iSize = (long long)atoll(pb); + m_size = (long long)atoll(pb); } - m_bPart = strstr(buffer, " part="); - if (!m_bPart) + m_part = strstr(buffer, " part="); + if (!m_part) { - m_bBody = true; - m_iBegin = 1; - m_iEnd = m_iSize; + m_body = true; + m_beginPos = 1; + m_endPos = m_size; } } - else if (m_bPart && !strncmp(buffer, "=ypart ", 7)) + else if (m_part && !strncmp(buffer, "=ypart ", 7)) { - m_bPart = true; - m_bBody = true; + m_part = true; + m_body = true; char* pb = strstr(buffer, " begin="); if (pb) { pb += 7; //=strlen(" begin=") - m_iBegin = (long long)atoll(pb); + m_beginPos = (long long)atoll(pb); } pb = strstr(buffer, " end="); if (pb) { pb += 5; //=strlen(" end=") - m_iEnd = (long long)atoll(pb); + m_endPos = (long long)atoll(pb); } } } @@ -234,29 +234,29 @@ BreakLoop: Decoder::EStatus YDecoder::Check() { - m_lCalculatedCRC ^= 0xFFFFFFFF; + m_calculatedCRC ^= 0xFFFFFFFF; - debug("Expected crc32=%x", m_lExpectedCRC); - debug("Calculated crc32=%x", m_lCalculatedCRC); + debug("Expected crc32=%x", m_expectedCRC); + debug("Calculated crc32=%x", m_calculatedCRC); - if (!m_bBegin) + if (!m_begin) { - return eNoBinaryData; + return dsNoBinaryData; } - else if (!m_bEnd) + else if (!m_end) { - return eArticleIncomplete; + return dsArticleIncomplete; } - else if (!m_bPart && m_iSize != m_iEndSize) + else if (!m_part && m_size != m_endSize) { - return eInvalidSize; + return dsInvalidSize; } - else if (m_bCrcCheck && m_bCrc && (m_lExpectedCRC != m_lCalculatedCRC)) + else if (m_crcCheck && m_crc && (m_expectedCRC != m_calculatedCRC)) { - return eCrcError; + return dsCrcError; } - return eFinished; + return dsFinished; } @@ -273,8 +273,8 @@ void UDecoder::Clear() { Decoder::Clear(); - m_bBody = false; - m_bEnd = false; + m_body = false; + m_end = false; } /* DecodeBuffer-function uses portions of code from tool UUDECODE by Clem Dye @@ -288,7 +288,7 @@ void UDecoder::Clear() int UDecoder::DecodeBuffer(char* buffer, int len) { - if (!m_bBody) + if (!m_body) { if (!strncmp(buffer, "begin ", 6)) { @@ -302,29 +302,29 @@ int UDecoder::DecodeBuffer(char* buffer, int len) // extracting filename char* pe; for (pe = pb; *pe != '\0' && *pe != '\n' && *pe != '\r'; pe++) ; - free(m_szArticleFilename); - m_szArticleFilename = (char*)malloc(pe - pb + 1); - strncpy(m_szArticleFilename, pb, pe - pb); - m_szArticleFilename[pe - pb] = '\0'; + free(m_articleFilename); + m_articleFilename = (char*)malloc(pe - pb + 1); + strncpy(m_articleFilename, pb, pe - pb); + m_articleFilename[pe - pb] = '\0'; - m_bBody = true; + m_body = true; return 0; } else if ((len == 62 || len == 63) && (buffer[62] == '\n' || buffer[62] == '\r') && *buffer == 'M') { - m_bBody = true; + m_body = true; } } - if (m_bBody && (!strncmp(buffer, "end ", 4) || *buffer == '`')) + if (m_body && (!strncmp(buffer, "end ", 4) || *buffer == '`')) { - m_bEnd = true; + m_end = true; } - if (m_bBody && !m_bEnd) + if (m_body && !m_end) { - int iEffLen = UU_DECODE_CHAR(buffer[0]); - if (iEffLen > len) + int effLen = UU_DECODE_CHAR(buffer[0]); + if (effLen > len) { // error; return 0; @@ -332,9 +332,9 @@ int UDecoder::DecodeBuffer(char* buffer, int len) char* iptr = buffer; char* optr = buffer; - for (++iptr; iEffLen > 0; iptr += 4, iEffLen -= 3) + for (++iptr; effLen > 0; iptr += 4, effLen -= 3) { - if (iEffLen >= 3) + if (effLen >= 3) { *optr++ = UU_DECODE_CHAR (iptr[0]) << 2 | UU_DECODE_CHAR (iptr[1]) >> 4; *optr++ = UU_DECODE_CHAR (iptr[1]) << 4 | UU_DECODE_CHAR (iptr[2]) >> 2; @@ -342,11 +342,11 @@ int UDecoder::DecodeBuffer(char* buffer, int len) } else { - if (iEffLen >= 1) + if (effLen >= 1) { *optr++ = UU_DECODE_CHAR (iptr[0]) << 2 | UU_DECODE_CHAR (iptr[1]) >> 4; } - if (iEffLen >= 2) + if (effLen >= 2) { *optr++ = UU_DECODE_CHAR (iptr[1]) << 4 | UU_DECODE_CHAR (iptr[2]) >> 2; } @@ -361,10 +361,10 @@ int UDecoder::DecodeBuffer(char* buffer, int len) Decoder::EStatus UDecoder::Check() { - if (!m_bBody) + if (!m_body) { - return eNoBinaryData; + return dsNoBinaryData; } - return eFinished; + return dsFinished; } diff --git a/daemon/nntp/Decoder.h b/daemon/nntp/Decoder.h index 94e8b095..728b954b 100644 --- a/daemon/nntp/Decoder.h +++ b/daemon/nntp/Decoder.h @@ -31,12 +31,12 @@ class Decoder public: enum EStatus { - eUnknownError, - eFinished, - eArticleIncomplete, - eCrcError, - eInvalidSize, - eNoBinaryData + dsUnknownError, + dsFinished, + dsArticleIncomplete, + dsCrcError, + dsInvalidSize, + dsNoBinaryData }; enum EFormat @@ -49,7 +49,7 @@ public: static const char* FormatNames[]; protected: - char* m_szArticleFilename; + char* m_articleFilename; public: Decoder(); @@ -57,44 +57,44 @@ public: virtual EStatus Check() = 0; virtual void Clear(); virtual int DecodeBuffer(char* buffer, int len) = 0; - const char* GetArticleFilename() { return m_szArticleFilename; } + const char* GetArticleFilename() { return m_articleFilename; } static EFormat DetectFormat(const char* buffer, int len); }; class YDecoder: public Decoder { protected: - bool m_bBegin; - bool m_bPart; - bool m_bBody; - bool m_bEnd; - bool m_bCrc; - unsigned long m_lExpectedCRC; - unsigned long m_lCalculatedCRC; - long long m_iBegin; - long long m_iEnd; - long long m_iSize; - long long m_iEndSize; - bool m_bCrcCheck; + bool m_begin; + bool m_part; + bool m_body; + bool m_end; + bool m_crc; + unsigned long m_expectedCRC; + unsigned long m_calculatedCRC; + long long m_beginPos; + long long m_endPos; + long long m_size; + long long m_endSize; + bool m_crcCheck; public: YDecoder(); virtual EStatus Check(); virtual void Clear(); virtual int DecodeBuffer(char* buffer, int len); - void SetCrcCheck(bool bCrcCheck) { m_bCrcCheck = bCrcCheck; } - long long GetBegin() { return m_iBegin; } - long long GetEnd() { return m_iEnd; } - long long GetSize() { return m_iSize; } - unsigned long GetExpectedCrc() { return m_lExpectedCRC; } - unsigned long GetCalculatedCrc() { return m_lCalculatedCRC; } + void SetCrcCheck(bool crcCheck) { m_crcCheck = crcCheck; } + long long GetBegin() { return m_beginPos; } + long long GetEnd() { return m_endPos; } + long long GetSize() { return m_size; } + unsigned long GetExpectedCrc() { return m_expectedCRC; } + unsigned long GetCalculatedCrc() { return m_calculatedCRC; } }; class UDecoder: public Decoder { private: - bool m_bBody; - bool m_bEnd; + bool m_body; + bool m_end; public: UDecoder(); diff --git a/daemon/nntp/NNTPConnection.cpp b/daemon/nntp/NNTPConnection.cpp index 2997b08b..a076a965 100644 --- a/daemon/nntp/NNTPConnection.cpp +++ b/daemon/nntp/NNTPConnection.cpp @@ -45,19 +45,19 @@ static const int CONNECTION_LINEBUFFER_SIZE = 1024*10; -NNTPConnection::NNTPConnection(NewsServer* pNewsServer) : Connection(pNewsServer->GetHost(), pNewsServer->GetPort(), pNewsServer->GetTLS()) +NNTPConnection::NNTPConnection(NewsServer* newsServer) : Connection(newsServer->GetHost(), newsServer->GetPort(), newsServer->GetTLS()) { - m_pNewsServer = pNewsServer; - m_szActiveGroup = NULL; - m_szLineBuf = (char*)malloc(CONNECTION_LINEBUFFER_SIZE); - m_bAuthError = false; - SetCipher(pNewsServer->GetCipher()); + m_newsServer = newsServer; + m_activeGroup = NULL; + m_lineBuf = (char*)malloc(CONNECTION_LINEBUFFER_SIZE); + m_authError = false; + SetCipher(newsServer->GetCipher()); } NNTPConnection::~NNTPConnection() { - free(m_szActiveGroup); - free(m_szLineBuf); + free(m_activeGroup); + free(m_lineBuf); } const char* NNTPConnection::Request(const char* req) @@ -67,11 +67,11 @@ const char* NNTPConnection::Request(const char* req) return NULL; } - m_bAuthError = false; + m_authError = false; WriteLine(req); - char* answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); + char* answer = ReadLine(m_lineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); if (!answer) { @@ -89,7 +89,7 @@ const char* NNTPConnection::Request(const char* req) //try again WriteLine(req); - answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); + answer = ReadLine(m_lineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); } return answer; @@ -97,32 +97,32 @@ const char* NNTPConnection::Request(const char* req) bool NNTPConnection::Authenticate() { - if (strlen(m_pNewsServer->GetUser()) == 0 || strlen(m_pNewsServer->GetPassword()) == 0) + if (strlen(m_newsServer->GetUser()) == 0 || strlen(m_newsServer->GetPassword()) == 0) { ReportError("Could not connect to %s: server requested authorization but username/password are not set in settings", - m_pNewsServer->GetHost(), false, 0); - m_bAuthError = true; + m_newsServer->GetHost(), false, 0); + m_authError = true; return false; } - m_bAuthError = !AuthInfoUser(0); - return !m_bAuthError; + m_authError = !AuthInfoUser(0); + return !m_authError; } -bool NNTPConnection::AuthInfoUser(int iRecur) +bool NNTPConnection::AuthInfoUser(int recur) { - if (iRecur > 10) + if (recur > 10) { return false; } char tmp[1024]; - snprintf(tmp, 1024, "AUTHINFO USER %s\r\n", m_pNewsServer->GetUser()); + snprintf(tmp, 1024, "AUTHINFO USER %s\r\n", m_newsServer->GetUser()); tmp[1024-1] = '\0'; WriteLine(tmp); - char* answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); + char* answer = ReadLine(m_lineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); if (!answer) { ReportErrorAnswer("Authorization for %s (%s) failed: Connection closed by remote host", NULL); @@ -136,11 +136,11 @@ bool NNTPConnection::AuthInfoUser(int iRecur) } else if (!strncmp(answer, "381", 3)) { - return AuthInfoPass(++iRecur); + return AuthInfoPass(++recur); } else if (!strncmp(answer, "480", 3)) { - return AuthInfoUser(++iRecur); + return AuthInfoUser(++recur); } if (char* p = strrchr(answer, '\r')) *p = '\0'; // remove last CRLF from error message @@ -152,20 +152,20 @@ bool NNTPConnection::AuthInfoUser(int iRecur) return false; } -bool NNTPConnection::AuthInfoPass(int iRecur) +bool NNTPConnection::AuthInfoPass(int recur) { - if (iRecur > 10) + if (recur > 10) { return false; } char tmp[1024]; - snprintf(tmp, 1024, "AUTHINFO PASS %s\r\n", m_pNewsServer->GetPassword()); + snprintf(tmp, 1024, "AUTHINFO PASS %s\r\n", m_newsServer->GetPassword()); tmp[1024-1] = '\0'; WriteLine(tmp); - char* answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); + char* answer = ReadLine(m_lineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); if (!answer) { ReportErrorAnswer("Authorization failed for %s (%s): Connection closed by remote host", NULL); @@ -178,7 +178,7 @@ bool NNTPConnection::AuthInfoPass(int iRecur) } else if (!strncmp(answer, "381", 3)) { - return AuthInfoPass(++iRecur); + return AuthInfoPass(++recur); } if (char* p = strrchr(answer, '\r')) *p = '\0'; // remove last CRLF from error message @@ -192,11 +192,11 @@ bool NNTPConnection::AuthInfoPass(int iRecur) const char* NNTPConnection::JoinGroup(const char* grp) { - if (m_szActiveGroup && !strcmp(m_szActiveGroup, grp)) + if (m_activeGroup && !strcmp(m_activeGroup, grp)) { // already in group - strcpy(m_szLineBuf, "211 "); - return m_szLineBuf; + strcpy(m_lineBuf, "211 "); + return m_lineBuf; } char tmp[1024]; @@ -208,8 +208,8 @@ const char* NNTPConnection::JoinGroup(const char* grp) if (answer && !strncmp(answer, "2", 1)) { debug("Changed group to %s on %s", grp, GetHost()); - free(m_szActiveGroup); - m_szActiveGroup = strdup(grp); + free(m_activeGroup); + m_activeGroup = strdup(grp); } else { @@ -223,7 +223,7 @@ bool NNTPConnection::Connect() { debug("Opening connection to %s", GetHost()); - if (m_eStatus == csConnected) + if (m_status == csConnected) { return true; } @@ -233,7 +233,7 @@ bool NNTPConnection::Connect() return false; } - char* answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); + char* answer = ReadLine(m_lineBuf, CONNECTION_LINEBUFFER_SIZE, NULL); if (!answer) { @@ -249,7 +249,7 @@ bool NNTPConnection::Connect() return false; } - if ((strlen(m_pNewsServer->GetUser()) > 0 && strlen(m_pNewsServer->GetPassword()) > 0) && + if ((strlen(m_newsServer->GetUser()) > 0 && strlen(m_newsServer->GetPassword()) > 0) && !Authenticate()) { return false; @@ -262,23 +262,23 @@ bool NNTPConnection::Connect() bool NNTPConnection::Disconnect() { - if (m_eStatus == csConnected) + if (m_status == csConnected) { - if (!m_bBroken) + if (!m_broken) { Request("quit\r\n"); } - free(m_szActiveGroup); - m_szActiveGroup = NULL; + free(m_activeGroup); + m_activeGroup = NULL; } return Connection::Disconnect(); } -void NNTPConnection::ReportErrorAnswer(const char* szMsgPrefix, const char* szAnswer) +void NNTPConnection::ReportErrorAnswer(const char* msgPrefix, const char* answer) { - char szErrStr[1024]; - snprintf(szErrStr, 1024, szMsgPrefix, m_pNewsServer->GetName(), m_pNewsServer->GetHost(), szAnswer); - szErrStr[1024-1] = '\0'; + char errStr[1024]; + snprintf(errStr, 1024, msgPrefix, m_newsServer->GetName(), m_newsServer->GetHost(), answer); + errStr[1024-1] = '\0'; - ReportError(szErrStr, NULL, false, 0); + ReportError(errStr, NULL, false, 0); } diff --git a/daemon/nntp/NNTPConnection.h b/daemon/nntp/NNTPConnection.h index d5b6ebd6..d99cd51c 100644 --- a/daemon/nntp/NNTPConnection.h +++ b/daemon/nntp/NNTPConnection.h @@ -33,26 +33,26 @@ class NNTPConnection : public Connection { private: - NewsServer* m_pNewsServer; - char* m_szActiveGroup; - char* m_szLineBuf; - bool m_bAuthError; + NewsServer* m_newsServer; + char* m_activeGroup; + char* m_lineBuf; + bool m_authError; void Clear(); - void ReportErrorAnswer(const char* szMsgPrefix, const char* szAnswer); + void ReportErrorAnswer(const char* msgPrefix, const char* answer); bool Authenticate(); - bool AuthInfoUser(int iRecur); - bool AuthInfoPass(int iRecur); + bool AuthInfoUser(int recur); + bool AuthInfoPass(int recur); public: - NNTPConnection(NewsServer* pNewsServer); + NNTPConnection(NewsServer* newsServer); virtual ~NNTPConnection(); virtual bool Connect(); virtual bool Disconnect(); - NewsServer* GetNewsServer() { return m_pNewsServer; } + NewsServer* GetNewsServer() { return m_newsServer; } const char* Request(const char* req); const char* JoinGroup(const char* grp); - bool GetAuthError() { return m_bAuthError; } + bool GetAuthError() { return m_authError; } }; diff --git a/daemon/nntp/NewsServer.cpp b/daemon/nntp/NewsServer.cpp index 1c9fafda..f8a8caba 100644 --- a/daemon/nntp/NewsServer.cpp +++ b/daemon/nntp/NewsServer.cpp @@ -39,44 +39,44 @@ #include "nzbget.h" #include "NewsServer.h" -NewsServer::NewsServer(int iID, bool bActive, const char* szName, const char* szHost, int iPort, - const char* szUser, const char* szPass, bool bJoinGroup, bool bTLS, - const char* szCipher, int iMaxConnections, int iRetention, int iLevel, int iGroup) +NewsServer::NewsServer(int id, bool active, const char* name, const char* host, int port, + const char* user, const char* pass, bool joinGroup, bool tLS, + const char* cipher, int maxConnections, int retention, int level, int group) { - m_iID = iID; - m_iStateID = 0; - m_bActive = bActive; - m_iPort = iPort; - m_iLevel = iLevel; - m_iNormLevel = iLevel; - m_iGroup = iGroup; - m_iMaxConnections = iMaxConnections; - m_bJoinGroup = bJoinGroup; - m_bTLS = bTLS; - m_szHost = strdup(szHost ? szHost : ""); - m_szUser = strdup(szUser ? szUser : ""); - m_szPassword = strdup(szPass ? szPass : ""); - m_szCipher = strdup(szCipher ? szCipher : ""); - m_iRetention = iRetention; - m_tBlockTime = 0; + m_id = id; + m_stateId = 0; + m_active = active; + m_port = port; + m_level = level; + m_normLevel = level; + m_group = group; + m_maxConnections = maxConnections; + m_joinGroup = joinGroup; + m_tLS = tLS; + m_host = strdup(host ? host : ""); + m_user = strdup(user ? user : ""); + m_password = strdup(pass ? pass : ""); + m_cipher = strdup(cipher ? cipher : ""); + m_retention = retention; + m_blockTime = 0; - if (szName && strlen(szName) > 0) + if (name && strlen(name) > 0) { - m_szName = strdup(szName); + m_name = strdup(name); } else { - m_szName = (char*)malloc(20); - snprintf(m_szName, 20, "server%i", iID); - m_szName[20-1] = '\0'; + m_name = (char*)malloc(20); + snprintf(m_name, 20, "server%i", id); + m_name[20-1] = '\0'; } } NewsServer::~NewsServer() { - free(m_szName); - free(m_szHost); - free(m_szUser); - free(m_szPassword); - free(m_szCipher); + free(m_name); + free(m_host); + free(m_user); + free(m_password); + free(m_cipher); } diff --git a/daemon/nntp/NewsServer.h b/daemon/nntp/NewsServer.h index 30a6ee58..a8f883c6 100644 --- a/daemon/nntp/NewsServer.h +++ b/daemon/nntp/NewsServer.h @@ -33,51 +33,51 @@ class NewsServer { private: - int m_iID; - int m_iStateID; - bool m_bActive; - char* m_szName; - int m_iGroup; - char* m_szHost; - int m_iPort; - char* m_szUser; - char* m_szPassword; - int m_iMaxConnections; - int m_iLevel; - int m_iNormLevel; - bool m_bJoinGroup; - bool m_bTLS; - char* m_szCipher; - int m_iRetention; - time_t m_tBlockTime; + int m_id; + int m_stateId; + bool m_active; + char* m_name; + int m_group; + char* m_host; + int m_port; + char* m_user; + char* m_password; + int m_maxConnections; + int m_level; + int m_normLevel; + bool m_joinGroup; + bool m_tLS; + char* m_cipher; + int m_retention; + time_t m_blockTime; public: - NewsServer(int iID, bool bActive, const char* szName, const char* szHost, int iPort, - const char* szUser, const char* szPass, bool bJoinGroup, - bool bTLS, const char* szCipher, int iMaxConnections, int iRetention, - int iLevel, int iGroup); + NewsServer(int id, bool active, const char* name, const char* host, int port, + const char* user, const char* pass, bool joinGroup, + bool tLS, const char* cipher, int maxConnections, int retention, + int level, int group); ~NewsServer(); - int GetID() { return m_iID; } - int GetStateID() { return m_iStateID; } - void SetStateID(int iStateID) { m_iStateID = iStateID; } - bool GetActive() { return m_bActive; } - void SetActive(bool bActive) { m_bActive = bActive; } - const char* GetName() { return m_szName; } - int GetGroup() { return m_iGroup; } - const char* GetHost() { return m_szHost; } - int GetPort() { return m_iPort; } - const char* GetUser() { return m_szUser; } - const char* GetPassword() { return m_szPassword; } - int GetMaxConnections() { return m_iMaxConnections; } - int GetLevel() { return m_iLevel; } - int GetNormLevel() { return m_iNormLevel; } - void SetNormLevel(int iLevel) { m_iNormLevel = iLevel; } - int GetJoinGroup() { return m_bJoinGroup; } - bool GetTLS() { return m_bTLS; } - const char* GetCipher() { return m_szCipher; } - int GetRetention() { return m_iRetention; } - time_t GetBlockTime() { return m_tBlockTime; } - void SetBlockTime(time_t tBlockTime) { m_tBlockTime = tBlockTime; } + int GetID() { return m_id; } + int GetStateID() { return m_stateId; } + void SetStateID(int stateId) { m_stateId = stateId; } + bool GetActive() { return m_active; } + void SetActive(bool active) { m_active = active; } + const char* GetName() { return m_name; } + int GetGroup() { return m_group; } + const char* GetHost() { return m_host; } + int GetPort() { return m_port; } + const char* GetUser() { return m_user; } + const char* GetPassword() { return m_password; } + int GetMaxConnections() { return m_maxConnections; } + int GetLevel() { return m_level; } + int GetNormLevel() { return m_normLevel; } + void SetNormLevel(int level) { m_normLevel = level; } + int GetJoinGroup() { return m_joinGroup; } + bool GetTLS() { return m_tLS; } + const char* GetCipher() { return m_cipher; } + int GetRetention() { return m_retention; } + time_t GetBlockTime() { return m_blockTime; } + void SetBlockTime(time_t blockTime) { m_blockTime = blockTime; } }; typedef std::vector Servers; diff --git a/daemon/nntp/ServerPool.cpp b/daemon/nntp/ServerPool.cpp index defa585f..5cd709c9 100644 --- a/daemon/nntp/ServerPool.cpp +++ b/daemon/nntp/ServerPool.cpp @@ -47,18 +47,18 @@ static const int CONNECTION_HOLD_SECODNS = 5; ServerPool::PooledConnection::PooledConnection(NewsServer* server) : NNTPConnection(server) { - m_bInUse = false; - m_tFreeTime = 0; + m_inUse = false; + m_freeTime = 0; } ServerPool::ServerPool() { debug("Creating ServerPool"); - m_iMaxNormLevel = 0; - m_iTimeout = 60; - m_iGeneration = 0; - m_iRetryInterval = 0; + m_maxNormLevel = 0; + m_timeout = 60; + m_generation = 0; + m_retryInterval = 0; g_pLog->RegisterDebuggable(this); } @@ -69,28 +69,28 @@ ServerPool::~ ServerPool() g_pLog->UnregisterDebuggable(this); - m_Levels.clear(); + m_levels.clear(); - for (Servers::iterator it = m_Servers.begin(); it != m_Servers.end(); it++) + for (Servers::iterator it = m_servers.begin(); it != m_servers.end(); it++) { delete *it; } - m_Servers.clear(); - m_SortedServers.clear(); + m_servers.clear(); + m_sortedServers.clear(); - for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); it++) + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); it++) { delete *it; } - m_Connections.clear(); + m_connections.clear(); } -void ServerPool::AddServer(NewsServer* pNewsServer) +void ServerPool::AddServer(NewsServer* newsServer) { debug("Adding server to ServerPool"); - m_Servers.push_back(pNewsServer); - m_SortedServers.push_back(pNewsServer); + m_servers.push_back(newsServer); + m_sortedServers.push_back(newsServer); } /* @@ -101,150 +101,150 @@ void ServerPool::AddServer(NewsServer* pNewsServer) **/ void ServerPool::NormalizeLevels() { - if (m_Servers.empty()) + if (m_servers.empty()) { return; } - std::sort(m_SortedServers.begin(), m_SortedServers.end(), CompareServers); + std::sort(m_sortedServers.begin(), m_sortedServers.end(), CompareServers); // find minimum level - int iMinLevel = m_SortedServers.front()->GetLevel(); - for (Servers::iterator it = m_SortedServers.begin(); it != m_SortedServers.end(); it++) + int minLevel = m_sortedServers.front()->GetLevel(); + for (Servers::iterator it = m_sortedServers.begin(); it != m_sortedServers.end(); it++) { - NewsServer* pNewsServer = *it; - if (pNewsServer->GetLevel() < iMinLevel) + NewsServer* newsServer = *it; + if (newsServer->GetLevel() < minLevel) { - iMinLevel = pNewsServer->GetLevel(); + minLevel = newsServer->GetLevel(); } } - m_iMaxNormLevel = 0; - int iLastLevel = iMinLevel; - for (Servers::iterator it = m_SortedServers.begin(); it != m_SortedServers.end(); it++) + m_maxNormLevel = 0; + int lastLevel = minLevel; + for (Servers::iterator it = m_sortedServers.begin(); it != m_sortedServers.end(); it++) { - NewsServer* pNewsServer = *it; - if ((pNewsServer->GetActive() && pNewsServer->GetMaxConnections() > 0) || - (pNewsServer->GetLevel() == iMinLevel)) + NewsServer* newsServer = *it; + if ((newsServer->GetActive() && newsServer->GetMaxConnections() > 0) || + (newsServer->GetLevel() == minLevel)) { - if (pNewsServer->GetLevel() != iLastLevel) + if (newsServer->GetLevel() != lastLevel) { - m_iMaxNormLevel++; + m_maxNormLevel++; } - pNewsServer->SetNormLevel(m_iMaxNormLevel); - iLastLevel = pNewsServer->GetLevel(); + newsServer->SetNormLevel(m_maxNormLevel); + lastLevel = newsServer->GetLevel(); } else { - pNewsServer->SetNormLevel(-1); + newsServer->SetNormLevel(-1); } } } -bool ServerPool::CompareServers(NewsServer* pServer1, NewsServer* pServer2) +bool ServerPool::CompareServers(NewsServer* server1, NewsServer* server2) { - return pServer1->GetLevel() < pServer2->GetLevel(); + return server1->GetLevel() < server2->GetLevel(); } void ServerPool::InitConnections() { debug("Initializing connections in ServerPool"); - m_mutexConnections.Lock(); + m_connectionsMutex.Lock(); NormalizeLevels(); - m_Levels.clear(); + m_levels.clear(); - for (Servers::iterator it = m_SortedServers.begin(); it != m_SortedServers.end(); it++) + for (Servers::iterator it = m_sortedServers.begin(); it != m_sortedServers.end(); it++) { - NewsServer* pNewsServer = *it; - pNewsServer->SetBlockTime(0); - int iNormLevel = pNewsServer->GetNormLevel(); - if (pNewsServer->GetNormLevel() > -1) + NewsServer* newsServer = *it; + newsServer->SetBlockTime(0); + int normLevel = newsServer->GetNormLevel(); + if (newsServer->GetNormLevel() > -1) { - if ((int)m_Levels.size() <= iNormLevel) + if ((int)m_levels.size() <= normLevel) { - m_Levels.push_back(0); + m_levels.push_back(0); } - if (pNewsServer->GetActive()) + if (newsServer->GetActive()) { - int iConnections = 0; + int connections = 0; - for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); it++) + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); it++) { - PooledConnection* pConnection = *it; - if (pConnection->GetNewsServer() == pNewsServer) + PooledConnection* connection = *it; + if (connection->GetNewsServer() == newsServer) { - iConnections++; + connections++; } } - for (int i = iConnections; i < pNewsServer->GetMaxConnections(); i++) + for (int i = connections; i < newsServer->GetMaxConnections(); i++) { - PooledConnection* pConnection = new PooledConnection(pNewsServer); - pConnection->SetTimeout(m_iTimeout); - m_Connections.push_back(pConnection); - iConnections++; + PooledConnection* connection = new PooledConnection(newsServer); + connection->SetTimeout(m_timeout); + m_connections.push_back(connection); + connections++; } - m_Levels[iNormLevel] += iConnections; + m_levels[normLevel] += connections; } } } - m_iGeneration++; + m_generation++; - m_mutexConnections.Unlock(); + m_connectionsMutex.Unlock(); } -NNTPConnection* ServerPool::GetConnection(int iLevel, NewsServer* pWantServer, Servers* pIgnoreServers) +NNTPConnection* ServerPool::GetConnection(int level, NewsServer* wantServer, Servers* ignoreServers) { - PooledConnection* pConnection = NULL; - m_mutexConnections.Lock(); + PooledConnection* connection = NULL; + m_connectionsMutex.Lock(); - time_t tCurTime = time(NULL); + time_t curTime = time(NULL); - if (iLevel < (int)m_Levels.size() && m_Levels[iLevel] > 0) + if (level < (int)m_levels.size() && m_levels[level] > 0) { Connections candidates; - candidates.reserve(m_Connections.size()); + candidates.reserve(m_connections.size()); - for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); it++) + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); it++) { - PooledConnection* pCandidateConnection = *it; - NewsServer* pCandidateServer = pCandidateConnection->GetNewsServer(); - if (!pCandidateConnection->GetInUse() && pCandidateServer->GetActive() && - pCandidateServer->GetNormLevel() == iLevel && - (!pWantServer || pCandidateServer == pWantServer || - (pWantServer->GetGroup() > 0 && pWantServer->GetGroup() == pCandidateServer->GetGroup())) && - (pCandidateConnection->GetStatus() == Connection::csConnected || - !pCandidateServer->GetBlockTime() || - pCandidateServer->GetBlockTime() + m_iRetryInterval <= tCurTime || - pCandidateServer->GetBlockTime() > tCurTime)) + PooledConnection* candidateConnection = *it; + NewsServer* candidateServer = candidateConnection->GetNewsServer(); + if (!candidateConnection->GetInUse() && candidateServer->GetActive() && + candidateServer->GetNormLevel() == level && + (!wantServer || candidateServer == wantServer || + (wantServer->GetGroup() > 0 && wantServer->GetGroup() == candidateServer->GetGroup())) && + (candidateConnection->GetStatus() == Connection::csConnected || + !candidateServer->GetBlockTime() || + candidateServer->GetBlockTime() + m_retryInterval <= curTime || + candidateServer->GetBlockTime() > curTime)) { // free connection found, check if it's not from the server which should be ignored - bool bUseConnection = true; - if (pIgnoreServers && !pWantServer) + bool useConnection = true; + if (ignoreServers && !wantServer) { - for (Servers::iterator it = pIgnoreServers->begin(); it != pIgnoreServers->end(); it++) + for (Servers::iterator it = ignoreServers->begin(); it != ignoreServers->end(); it++) { - NewsServer* pIgnoreServer = *it; - if (pIgnoreServer == pCandidateServer || - (pIgnoreServer->GetGroup() > 0 && pIgnoreServer->GetGroup() == pCandidateServer->GetGroup() && - pIgnoreServer->GetNormLevel() == pCandidateServer->GetNormLevel())) + NewsServer* ignoreServer = *it; + if (ignoreServer == candidateServer || + (ignoreServer->GetGroup() > 0 && ignoreServer->GetGroup() == candidateServer->GetGroup() && + ignoreServer->GetNormLevel() == candidateServer->GetNormLevel())) { - bUseConnection = false; + useConnection = false; break; } } } - pCandidateServer->SetBlockTime(0); + candidateServer->SetBlockTime(0); - if (bUseConnection) + if (useConnection) { - candidates.push_back(pCandidateConnection); + candidates.push_back(candidateConnection); } } } @@ -254,88 +254,88 @@ NNTPConnection* ServerPool::GetConnection(int iLevel, NewsServer* pWantServer, S // Peeking a random free connection. This is better than taking the first // available connection because provides better distribution across news servers, // especially when one of servers becomes unavailable or doesn't have requested articles. - int iRandomIndex = rand() % candidates.size(); - pConnection = candidates[iRandomIndex]; - pConnection->SetInUse(true); + int randomIndex = rand() % candidates.size(); + connection = candidates[randomIndex]; + connection->SetInUse(true); } - if (pConnection) + if (connection) { - m_Levels[iLevel]--; + m_levels[level]--; } } - m_mutexConnections.Unlock(); + m_connectionsMutex.Unlock(); - return pConnection; + return connection; } -void ServerPool::FreeConnection(NNTPConnection* pConnection, bool bUsed) +void ServerPool::FreeConnection(NNTPConnection* connection, bool used) { - if (bUsed) + if (used) { debug("Freeing used connection"); } - m_mutexConnections.Lock(); + m_connectionsMutex.Lock(); - ((PooledConnection*)pConnection)->SetInUse(false); - if (bUsed) + ((PooledConnection*)connection)->SetInUse(false); + if (used) { - ((PooledConnection*)pConnection)->SetFreeTimeNow(); + ((PooledConnection*)connection)->SetFreeTimeNow(); } - if (pConnection->GetNewsServer()->GetNormLevel() > -1 && pConnection->GetNewsServer()->GetActive()) + if (connection->GetNewsServer()->GetNormLevel() > -1 && connection->GetNewsServer()->GetActive()) { - m_Levels[pConnection->GetNewsServer()->GetNormLevel()]++; + m_levels[connection->GetNewsServer()->GetNormLevel()]++; } - m_mutexConnections.Unlock(); + m_connectionsMutex.Unlock(); } -void ServerPool::BlockServer(NewsServer* pNewsServer) +void ServerPool::BlockServer(NewsServer* newsServer) { - m_mutexConnections.Lock(); - time_t tCurTime = time(NULL); - bool bNewBlock = pNewsServer->GetBlockTime() != tCurTime; - pNewsServer->SetBlockTime(tCurTime); - m_mutexConnections.Unlock(); + m_connectionsMutex.Lock(); + time_t curTime = time(NULL); + bool newBlock = newsServer->GetBlockTime() != curTime; + newsServer->SetBlockTime(curTime); + m_connectionsMutex.Unlock(); - if (bNewBlock && m_iRetryInterval > 0) + if (newBlock && m_retryInterval > 0) { - warn("Blocking %s (%s) for %i sec", pNewsServer->GetName(), pNewsServer->GetHost(), m_iRetryInterval); + warn("Blocking %s (%s) for %i sec", newsServer->GetName(), newsServer->GetHost(), m_retryInterval); } } void ServerPool::CloseUnusedConnections() { - m_mutexConnections.Lock(); + m_connectionsMutex.Lock(); time_t curtime = ::time(NULL); // close and free all connections of servers which were disabled since the last check int i = 0; - for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); ) + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); ) { - PooledConnection* pConnection = *it; - bool bDeleted = false; + PooledConnection* connection = *it; + bool deleted = false; - if (!pConnection->GetInUse() && - (pConnection->GetNewsServer()->GetNormLevel() == -1 || - !pConnection->GetNewsServer()->GetActive())) + if (!connection->GetInUse() && + (connection->GetNewsServer()->GetNormLevel() == -1 || + !connection->GetNewsServer()->GetActive())) { - debug("Closing (and deleting) unused connection to server%i", pConnection->GetNewsServer()->GetID()); - if (pConnection->GetStatus() == Connection::csConnected) + debug("Closing (and deleting) unused connection to server%i", connection->GetNewsServer()->GetID()); + if (connection->GetStatus() == Connection::csConnected) { - pConnection->Disconnect(); + connection->Disconnect(); } - delete pConnection; - m_Connections.erase(it); - it = m_Connections.begin() + i; - bDeleted = true; + delete connection; + m_connections.erase(it); + it = m_connections.begin() + i; + deleted = true; } - if (!bDeleted) + if (!deleted) { it++; i++; @@ -343,27 +343,27 @@ void ServerPool::CloseUnusedConnections() } // close all opened connections on levels not having any in-use connections - for (int iLevel = 0; iLevel <= m_iMaxNormLevel; iLevel++) + for (int level = 0; level <= m_maxNormLevel; level++) { // check if we have in-use connections on the level - bool bHasInUseConnections = false; - int iInactiveTime = 0; - for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); it++) + bool hasInUseConnections = false; + int inactiveTime = 0; + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); it++) { - PooledConnection* pConnection = *it; - if (pConnection->GetNewsServer()->GetNormLevel() == iLevel) + PooledConnection* connection = *it; + if (connection->GetNewsServer()->GetNormLevel() == level) { - if (pConnection->GetInUse()) + if (connection->GetInUse()) { - bHasInUseConnections = true; + hasInUseConnections = true; break; } else { - int tdiff = (int)(curtime - pConnection->GetFreeTime()); - if (tdiff > iInactiveTime) + int tdiff = (int)(curtime - connection->GetFreeTime()); + if (tdiff > inactiveTime) { - iInactiveTime = tdiff; + inactiveTime = tdiff; } } } @@ -371,22 +371,22 @@ void ServerPool::CloseUnusedConnections() // if there are no in-use connections on the level and the hold time out has // expired - close all connections of the level. - if (!bHasInUseConnections && iInactiveTime > CONNECTION_HOLD_SECODNS) + if (!hasInUseConnections && inactiveTime > CONNECTION_HOLD_SECODNS) { - for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); it++) + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); it++) { - PooledConnection* pConnection = *it; - if (pConnection->GetNewsServer()->GetNormLevel() == iLevel && - pConnection->GetStatus() == Connection::csConnected) + PooledConnection* connection = *it; + if (connection->GetNewsServer()->GetNormLevel() == level && + connection->GetStatus() == Connection::csConnected) { - debug("Closing (and keeping) unused connection to server%i", pConnection->GetNewsServer()->GetID()); - pConnection->Disconnect(); + debug("Closing (and keeping) unused connection to server%i", connection->GetNewsServer()->GetID()); + connection->Disconnect(); } } } } - m_mutexConnections.Unlock(); + m_connectionsMutex.Unlock(); } void ServerPool::Changed() @@ -401,39 +401,39 @@ void ServerPool::LogDebugInfo() { info(" ---------- ServerPool"); - info(" Max-Level: %i", m_iMaxNormLevel); + info(" Max-Level: %i", m_maxNormLevel); - m_mutexConnections.Lock(); + m_connectionsMutex.Lock(); - time_t tCurTime = time(NULL); + time_t curTime = time(NULL); - info(" Servers: %i", m_Servers.size()); - for (Servers::iterator it = m_Servers.begin(); it != m_Servers.end(); it++) + info(" Servers: %i", m_servers.size()); + for (Servers::iterator it = m_servers.begin(); it != m_servers.end(); it++) { - NewsServer* pNewsServer = *it; - info(" %i) %s (%s): Level=%i, NormLevel=%i, BlockSec=%i", pNewsServer->GetID(), pNewsServer->GetName(), - pNewsServer->GetHost(), pNewsServer->GetLevel(), pNewsServer->GetNormLevel(), - pNewsServer->GetBlockTime() && pNewsServer->GetBlockTime() + m_iRetryInterval > tCurTime ? - pNewsServer->GetBlockTime() + m_iRetryInterval - tCurTime : 0); + NewsServer* newsServer = *it; + info(" %i) %s (%s): Level=%i, NormLevel=%i, BlockSec=%i", newsServer->GetID(), newsServer->GetName(), + newsServer->GetHost(), newsServer->GetLevel(), newsServer->GetNormLevel(), + newsServer->GetBlockTime() && newsServer->GetBlockTime() + m_retryInterval > curTime ? + newsServer->GetBlockTime() + m_retryInterval - curTime : 0); } - info(" Levels: %i", m_Levels.size()); + info(" Levels: %i", m_levels.size()); int index = 0; - for (Levels::iterator it = m_Levels.begin(); it != m_Levels.end(); it++, index++) + for (Levels::iterator it = m_levels.begin(); it != m_levels.end(); it++, index++) { - int iSize = *it; - info(" %i: Free connections=%i", index, iSize); + int size = *it; + info(" %i: Free connections=%i", index, size); } - info(" Connections: %i", m_Connections.size()); - for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); it++) + info(" Connections: %i", m_connections.size()); + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); it++) { - PooledConnection* pConnection = *it; - info(" %i) %s (%s): Level=%i, NormLevel=%i, InUse:%i", pConnection->GetNewsServer()->GetID(), - pConnection->GetNewsServer()->GetName(), pConnection->GetNewsServer()->GetHost(), - pConnection->GetNewsServer()->GetLevel(), pConnection->GetNewsServer()->GetNormLevel(), - (int)pConnection->GetInUse()); + PooledConnection* connection = *it; + info(" %i) %s (%s): Level=%i, NormLevel=%i, InUse:%i", connection->GetNewsServer()->GetID(), + connection->GetNewsServer()->GetName(), connection->GetNewsServer()->GetHost(), + connection->GetNewsServer()->GetLevel(), connection->GetNewsServer()->GetNormLevel(), + (int)connection->GetInUse()); } - m_mutexConnections.Unlock(); + m_connectionsMutex.Unlock(); } diff --git a/daemon/nntp/ServerPool.h b/daemon/nntp/ServerPool.h index 3ee0c122..ef390f66 100644 --- a/daemon/nntp/ServerPool.h +++ b/daemon/nntp/ServerPool.h @@ -41,31 +41,31 @@ private: class PooledConnection : public NNTPConnection { private: - bool m_bInUse; - time_t m_tFreeTime; + bool m_inUse; + time_t m_freeTime; public: PooledConnection(NewsServer* server); - bool GetInUse() { return m_bInUse; } - void SetInUse(bool bInUse) { m_bInUse = bInUse; } - time_t GetFreeTime() { return m_tFreeTime; } - void SetFreeTimeNow() { m_tFreeTime = ::time(NULL); } + bool GetInUse() { return m_inUse; } + void SetInUse(bool inUse) { m_inUse = inUse; } + time_t GetFreeTime() { return m_freeTime; } + void SetFreeTimeNow() { m_freeTime = ::time(NULL); } }; typedef std::vector Levels; typedef std::vector Connections; - Servers m_Servers; - Servers m_SortedServers; - Connections m_Connections; - Levels m_Levels; - int m_iMaxNormLevel; - Mutex m_mutexConnections; - int m_iTimeout; - int m_iRetryInterval; - int m_iGeneration; + Servers m_servers; + Servers m_sortedServers; + Connections m_connections; + Levels m_levels; + int m_maxNormLevel; + Mutex m_connectionsMutex; + int m_timeout; + int m_retryInterval; + int m_generation; void NormalizeLevels(); - static bool CompareServers(NewsServer* pServer1, NewsServer* pServer2); + static bool CompareServers(NewsServer* server1, NewsServer* server2); protected: virtual void LogDebugInfo(); @@ -73,18 +73,18 @@ protected: public: ServerPool(); ~ServerPool(); - void SetTimeout(int iTimeout) { m_iTimeout = iTimeout; } - void SetRetryInterval(int iRetryInterval) { m_iRetryInterval = iRetryInterval; } - void AddServer(NewsServer* pNewsServer); + void SetTimeout(int timeout) { m_timeout = timeout; } + void SetRetryInterval(int retryInterval) { m_retryInterval = retryInterval; } + void AddServer(NewsServer* newsServer); void InitConnections(); - int GetMaxNormLevel() { return m_iMaxNormLevel; } - Servers* GetServers() { return &m_Servers; } // Only for read access (no lockings) - NNTPConnection* GetConnection(int iLevel, NewsServer* pWantServer, Servers* pIgnoreServers); - void FreeConnection(NNTPConnection* pConnection, bool bUsed); + int GetMaxNormLevel() { return m_maxNormLevel; } + Servers* GetServers() { return &m_servers; } // Only for read access (no lockings) + NNTPConnection* GetConnection(int level, NewsServer* wantServer, Servers* ignoreServers); + void FreeConnection(NNTPConnection* connection, bool used); void CloseUnusedConnections(); void Changed(); - int GetGeneration() { return m_iGeneration; } - void BlockServer(NewsServer* pNewsServer); + int GetGeneration() { return m_generation; } + void BlockServer(NewsServer* newsServer); }; extern ServerPool* g_pServerPool; diff --git a/daemon/nntp/StatMeter.cpp b/daemon/nntp/StatMeter.cpp index bf44c51d..335833fc 100644 --- a/daemon/nntp/StatMeter.cpp +++ b/daemon/nntp/StatMeter.cpp @@ -47,121 +47,121 @@ static const int DAYS_IN_TWENTY_YEARS = 366*20; ServerVolume::ServerVolume() { - m_BytesPerSeconds.resize(60); - m_BytesPerMinutes.resize(60); - m_BytesPerHours.resize(24); - m_BytesPerDays.resize(0); - m_iFirstDay = 0; - m_tDataTime = 0; - m_lTotalBytes = 0; - m_lCustomBytes = 0; - m_tCustomTime = time(NULL); - m_iSecSlot = 0; - m_iMinSlot = 0; - m_iHourSlot = 0; - m_iDaySlot = 0; + m_bytesPerSeconds.resize(60); + m_bytesPerMinutes.resize(60); + m_bytesPerHours.resize(24); + m_bytesPerDays.resize(0); + m_firstDay = 0; + m_dataTime = 0; + m_totalBytes = 0; + m_customBytes = 0; + m_customTime = time(NULL); + m_secSlot = 0; + m_minSlot = 0; + m_hourSlot = 0; + m_daySlot = 0; } -void ServerVolume::CalcSlots(time_t tLocCurTime) +void ServerVolume::CalcSlots(time_t locCurTime) { - m_iSecSlot = (int)tLocCurTime % 60; - m_iMinSlot = ((int)tLocCurTime / 60) % 60; - m_iHourSlot = ((int)tLocCurTime % 86400) / 3600; - int iDaysSince1970 = (int)tLocCurTime / 86400; - m_iDaySlot = iDaysSince1970 - DAYS_UP_TO_2013_JAN_1 + 1; - if (0 <= m_iDaySlot && m_iDaySlot < DAYS_IN_TWENTY_YEARS) + m_secSlot = (int)locCurTime % 60; + m_minSlot = ((int)locCurTime / 60) % 60; + m_hourSlot = ((int)locCurTime % 86400) / 3600; + int daysSince1970 = (int)locCurTime / 86400; + m_daySlot = daysSince1970 - DAYS_UP_TO_2013_JAN_1 + 1; + if (0 <= m_daySlot && m_daySlot < DAYS_IN_TWENTY_YEARS) { - int iCurDay = iDaysSince1970; - if (m_iFirstDay == 0 || m_iFirstDay > iCurDay) + int curDay = daysSince1970; + if (m_firstDay == 0 || m_firstDay > curDay) { - m_iFirstDay = iCurDay; + m_firstDay = curDay; } - m_iDaySlot = iCurDay - m_iFirstDay; - if (m_iDaySlot + 1 > (int)m_BytesPerDays.size()) + m_daySlot = curDay - m_firstDay; + if (m_daySlot + 1 > (int)m_bytesPerDays.size()) { - m_BytesPerDays.resize(m_iDaySlot + 1); + m_bytesPerDays.resize(m_daySlot + 1); } } else { - m_iDaySlot = -1; + m_daySlot = -1; } } -void ServerVolume::AddData(int iBytes) +void ServerVolume::AddData(int bytes) { - time_t tCurTime = time(NULL); - time_t tLocCurTime = tCurTime + g_pOptions->GetLocalTimeOffset(); - time_t tLocDataTime = m_tDataTime + g_pOptions->GetLocalTimeOffset(); + time_t curTime = time(NULL); + time_t locCurTime = curTime + g_pOptions->GetLocalTimeOffset(); + time_t locDataTime = m_dataTime + g_pOptions->GetLocalTimeOffset(); - int iLastMinSlot = m_iMinSlot; - int iLastHourSlot = m_iHourSlot; + int lastMinSlot = m_minSlot; + int lastHourSlot = m_hourSlot; - CalcSlots(tLocCurTime); + CalcSlots(locCurTime); - if (tLocCurTime != tLocDataTime) + if (locCurTime != locDataTime) { // clear seconds/minutes/hours slots if necessary // also handle the backwards changes of system clock - int iTotalDelta = (int)(tLocCurTime - tLocDataTime); - int iDeltaSign = iTotalDelta >= 0 ? 1 : -1; - iTotalDelta = abs(iTotalDelta); + int totalDelta = (int)(locCurTime - locDataTime); + int deltaSign = totalDelta >= 0 ? 1 : -1; + totalDelta = abs(totalDelta); - int iSecDelta = iTotalDelta; - if (iDeltaSign < 0) iSecDelta++; - if (iSecDelta >= 60) iSecDelta = 60; - for (int i = 0; i < iSecDelta; i++) + int secDelta = totalDelta; + if (deltaSign < 0) secDelta++; + if (secDelta >= 60) secDelta = 60; + for (int i = 0; i < secDelta; i++) { - int iNulSlot = m_iSecSlot - i * iDeltaSign; - if (iNulSlot < 0) iNulSlot += 60; - if (iNulSlot >= 60) iNulSlot -= 60; - m_BytesPerSeconds[iNulSlot] = 0; + int nulSlot = m_secSlot - i * deltaSign; + if (nulSlot < 0) nulSlot += 60; + if (nulSlot >= 60) nulSlot -= 60; + m_bytesPerSeconds[nulSlot] = 0; } - int iMinDelta = iTotalDelta / 60; - if (iDeltaSign < 0) iMinDelta++; - if (abs(iMinDelta) >= 60) iMinDelta = 60; - if (iMinDelta == 0 && m_iMinSlot != iLastMinSlot) iMinDelta = 1; - for (int i = 0; i < iMinDelta; i++) + int minDelta = totalDelta / 60; + if (deltaSign < 0) minDelta++; + if (abs(minDelta) >= 60) minDelta = 60; + if (minDelta == 0 && m_minSlot != lastMinSlot) minDelta = 1; + for (int i = 0; i < minDelta; i++) { - int iNulSlot = m_iMinSlot - i * iDeltaSign; - if (iNulSlot < 0) iNulSlot += 60; - if (iNulSlot >= 60) iNulSlot -= 60; - m_BytesPerMinutes[iNulSlot] = 0; + int nulSlot = m_minSlot - i * deltaSign; + if (nulSlot < 0) nulSlot += 60; + if (nulSlot >= 60) nulSlot -= 60; + m_bytesPerMinutes[nulSlot] = 0; } - int iHourDelta = iTotalDelta / (60 * 60); - if (iDeltaSign < 0) iHourDelta++; - if (iHourDelta >= 24) iHourDelta = 24; - if (iHourDelta == 0 && m_iHourSlot != iLastHourSlot) iHourDelta = 1; - for (int i = 0; i < iHourDelta; i++) + int hourDelta = totalDelta / (60 * 60); + if (deltaSign < 0) hourDelta++; + if (hourDelta >= 24) hourDelta = 24; + if (hourDelta == 0 && m_hourSlot != lastHourSlot) hourDelta = 1; + for (int i = 0; i < hourDelta; i++) { - int iNulSlot = m_iHourSlot - i * iDeltaSign; - if (iNulSlot < 0) iNulSlot += 24; - if (iNulSlot >= 24) iNulSlot -= 24; - m_BytesPerHours[iNulSlot] = 0; + int nulSlot = m_hourSlot - i * deltaSign; + if (nulSlot < 0) nulSlot += 24; + if (nulSlot >= 24) nulSlot -= 24; + m_bytesPerHours[nulSlot] = 0; } } // add bytes to every slot - m_BytesPerSeconds[m_iSecSlot] += iBytes; - m_BytesPerMinutes[m_iMinSlot] += iBytes; - m_BytesPerHours[m_iHourSlot] += iBytes; - if (m_iDaySlot >= 0) + m_bytesPerSeconds[m_secSlot] += bytes; + m_bytesPerMinutes[m_minSlot] += bytes; + m_bytesPerHours[m_hourSlot] += bytes; + if (m_daySlot >= 0) { - m_BytesPerDays[m_iDaySlot] += iBytes; + m_bytesPerDays[m_daySlot] += bytes; } - m_lTotalBytes += iBytes; - m_lCustomBytes += iBytes; + m_totalBytes += bytes; + m_customBytes += bytes; - m_tDataTime = tCurTime; + m_dataTime = curTime; } void ServerVolume::ResetCustom() { - m_lCustomBytes = 0; - m_tCustomTime = time(NULL); + m_customBytes = 0; + m_customTime = time(NULL); } void ServerVolume::LogDebugInfo() @@ -172,36 +172,36 @@ void ServerVolume::LogDebugInfo() for (int i = 0; i < 60; i++) { - char szNum[30]; - snprintf(szNum, 30, "[%i]=%lli ", i, m_BytesPerSeconds[i]); - msg.Append(szNum); + char num[30]; + snprintf(num, 30, "[%i]=%lli ", i, m_bytesPerSeconds[i]); + msg.Append(num); } info("Secs: %s", msg.GetBuffer()); msg.Clear(); for (int i = 0; i < 60; i++) { - char szNum[30]; - snprintf(szNum, 30, "[%i]=%lli ", i, m_BytesPerMinutes[i]); - msg.Append(szNum); + char num[30]; + snprintf(num, 30, "[%i]=%lli ", i, m_bytesPerMinutes[i]); + msg.Append(num); } info("Mins: %s", msg.GetBuffer()); msg.Clear(); for (int i = 0; i < 24; i++) { - char szNum[30]; - snprintf(szNum, 30, "[%i]=%lli ", i, m_BytesPerHours[i]); - msg.Append(szNum); + char num[30]; + snprintf(num, 30, "[%i]=%lli ", i, m_bytesPerHours[i]); + msg.Append(num); } info("Hours: %s", msg.GetBuffer()); msg.Clear(); - for (int i = 0; i < (int)m_BytesPerDays.size(); i++) + for (int i = 0; i < (int)m_bytesPerDays.size(); i++) { - char szNum[30]; - snprintf(szNum, 30, "[%i]=%lli ", m_iFirstDay + i, m_BytesPerDays[i]); - msg.Append(szNum); + char num[30]; + snprintf(num, 30, "[%i]=%lli ", m_firstDay + i, m_bytesPerDays[i]); + msg.Append(num); } info("Days: %s", msg.GetBuffer()); } @@ -212,14 +212,14 @@ StatMeter::StatMeter() ResetSpeedStat(); - m_iAllBytes = 0; - m_tStartDownload = 0; - m_tPausedFrom = 0; - m_bStandBy = true; - m_tStartServer = 0; - m_tLastCheck = 0; - m_tLastTimeOffset = 0; - m_bStatChanged = false; + m_allBytes = 0; + m_startDownload = 0; + m_pausedFrom = 0; + m_standBy = true; + m_startServer = 0; + m_lastCheck = 0; + m_lastTimeOffset = 0; + m_statChanged = false; g_pLog->RegisterDebuggable(this); } @@ -231,7 +231,7 @@ StatMeter::~StatMeter() g_pLog->UnregisterDebuggable(this); - for (ServerVolumes::iterator it = m_ServerVolumes.begin(); it != m_ServerVolumes.end(); it++) + for (ServerVolumes::iterator it = m_serverVolumes.begin(); it != m_serverVolumes.end(); it++) { delete *it; } @@ -241,31 +241,31 @@ StatMeter::~StatMeter() void StatMeter::Init() { - m_tStartServer = time(NULL); - m_tLastCheck = m_tStartServer; + m_startServer = time(NULL); + m_lastCheck = m_startServer; AdjustTimeOffset(); - m_ServerVolumes.resize(1 + g_pServerPool->GetServers()->size()); - m_ServerVolumes[0] = new ServerVolume(); + m_serverVolumes.resize(1 + g_pServerPool->GetServers()->size()); + m_serverVolumes[0] = new ServerVolume(); for (Servers::iterator it = g_pServerPool->GetServers()->begin(); it != g_pServerPool->GetServers()->end(); it++) { - NewsServer* pServer = *it; - m_ServerVolumes[pServer->GetID()] = new ServerVolume(); + NewsServer* server = *it; + m_serverVolumes[server->GetID()] = new ServerVolume(); } } void StatMeter::AdjustTimeOffset() { - time_t tUtcTime = time(NULL); + time_t utcTime = time(NULL); tm tmSplittedTime; - gmtime_r(&tUtcTime, &tmSplittedTime); + gmtime_r(&utcTime, &tmSplittedTime); tmSplittedTime.tm_isdst = -1; - time_t tLocTime = mktime(&tmSplittedTime); - time_t tLocalTimeDelta = tUtcTime - tLocTime; - g_pOptions->SetLocalTimeOffset((int)tLocalTimeDelta + g_pOptions->GetTimeCorrection()); - m_tLastTimeOffset = tUtcTime; + time_t locTime = mktime(&tmSplittedTime); + time_t localTimeDelta = utcTime - locTime; + g_pOptions->SetLocalTimeOffset((int)localTimeDelta + g_pOptions->GetTimeCorrection()); + m_lastTimeOffset = utcTime; - debug("UTC delta: %i (%i+%i)", g_pOptions->GetLocalTimeOffset(), (int)tLocalTimeDelta, g_pOptions->GetTimeCorrection()); + debug("UTC delta: %i (%i+%i)", g_pOptions->GetLocalTimeOffset(), (int)localTimeDelta, g_pOptions->GetTimeCorrection()); } /* @@ -275,20 +275,20 @@ void StatMeter::AdjustTimeOffset() */ void StatMeter::IntervalCheck() { - time_t m_tCurTime = time(NULL); - time_t tDiff = m_tCurTime - m_tLastCheck; - if (tDiff > 60 || tDiff < 0) + time_t m_curTime = time(NULL); + time_t diff = m_curTime - m_lastCheck; + if (diff > 60 || diff < 0) { - m_tStartServer += tDiff + 1; // "1" because the method is called once per second - if (m_tStartDownload != 0 && !m_bStandBy) + m_startServer += diff + 1; // "1" because the method is called once per second + if (m_startDownload != 0 && !m_standBy) { - m_tStartDownload += tDiff + 1; + m_startDownload += diff + 1; } AdjustTimeOffset(); } - else if (m_tLastTimeOffset > m_tCurTime || - m_tCurTime - m_tLastTimeOffset > 60 * 60 * 3 || - (m_tCurTime - m_tLastTimeOffset > 60 && !m_bStandBy)) + else if (m_lastTimeOffset > m_curTime || + m_curTime - m_lastTimeOffset > 60 * 60 * 3 || + (m_curTime - m_lastTimeOffset > 60 && !m_standBy)) { // checking time zone settings may prevent the device from entering sleep/hibernate mode // check every minute if not in standby @@ -296,226 +296,226 @@ void StatMeter::IntervalCheck() AdjustTimeOffset(); } - m_tLastCheck = m_tCurTime; + m_lastCheck = m_curTime; - if (m_bStatChanged) + if (m_statChanged) { Save(); } } -void StatMeter::EnterLeaveStandBy(bool bEnter) +void StatMeter::EnterLeaveStandBy(bool enter) { - m_mutexStat.Lock(); - m_bStandBy = bEnter; - if (bEnter) + m_statMutex.Lock(); + m_standBy = enter; + if (enter) { - m_tPausedFrom = time(NULL); + m_pausedFrom = time(NULL); } else { - if (m_tStartDownload == 0) + if (m_startDownload == 0) { - m_tStartDownload = time(NULL); + m_startDownload = time(NULL); } else { - m_tStartDownload += time(NULL) - m_tPausedFrom; + m_startDownload += time(NULL) - m_pausedFrom; } - m_tPausedFrom = 0; + m_pausedFrom = 0; ResetSpeedStat(); } - m_mutexStat.Unlock(); + m_statMutex.Unlock(); } -void StatMeter::CalcTotalStat(int* iUpTimeSec, int* iDnTimeSec, long long* iAllBytes, bool* bStandBy) +void StatMeter::CalcTotalStat(int* upTimeSec, int* dnTimeSec, long long* allBytes, bool* standBy) { - m_mutexStat.Lock(); - if (m_tStartServer > 0) + m_statMutex.Lock(); + if (m_startServer > 0) { - *iUpTimeSec = (int)(time(NULL) - m_tStartServer); + *upTimeSec = (int)(time(NULL) - m_startServer); } else { - *iUpTimeSec = 0; + *upTimeSec = 0; } - *bStandBy = m_bStandBy; - if (m_bStandBy) + *standBy = m_standBy; + if (m_standBy) { - *iDnTimeSec = (int)(m_tPausedFrom - m_tStartDownload); + *dnTimeSec = (int)(m_pausedFrom - m_startDownload); } else { - *iDnTimeSec = (int)(time(NULL) - m_tStartDownload); + *dnTimeSec = (int)(time(NULL) - m_startDownload); } - *iAllBytes = m_iAllBytes; - m_mutexStat.Unlock(); + *allBytes = m_allBytes; + m_statMutex.Unlock(); } // Average speed in last 30 seconds int StatMeter::CalcCurrentDownloadSpeed() { - if (m_bStandBy) + if (m_standBy) { return 0; } - int iTimeDiff = (int)time(NULL) - m_iSpeedStartTime * SPEEDMETER_SLOTSIZE; - if (iTimeDiff == 0) + int timeDiff = (int)time(NULL) - m_speedStartTime * SPEEDMETER_SLOTSIZE; + if (timeDiff == 0) { return 0; } - return (int)(m_iSpeedTotalBytes / iTimeDiff); + return (int)(m_speedTotalBytes / timeDiff); } // Amount of data downloaded in current second int StatMeter::CalcMomentaryDownloadSpeed() { - time_t tCurTime = time(NULL); - int iSpeed = tCurTime == m_tCurSecTime ? m_iCurSecBytes : 0; - return iSpeed; + time_t curTime = time(NULL); + int speed = curTime == m_curSecTime ? m_curSecBytes : 0; + return speed; } -void StatMeter::AddSpeedReading(int iBytes) +void StatMeter::AddSpeedReading(int bytes) { - time_t tCurTime = time(NULL); - int iNowSlot = (int)tCurTime / SPEEDMETER_SLOTSIZE; + time_t curTime = time(NULL); + int nowSlot = (int)curTime / SPEEDMETER_SLOTSIZE; if (g_pOptions->GetAccurateRate()) { - m_mutexSpeed.Lock(); + m_speedMutex.Lock(); } - if (tCurTime != m_tCurSecTime) + if (curTime != m_curSecTime) { - m_tCurSecTime = tCurTime; - m_iCurSecBytes = 0; + m_curSecTime = curTime; + m_curSecBytes = 0; } - m_iCurSecBytes += iBytes; + m_curSecBytes += bytes; - while (iNowSlot > m_iSpeedTime[m_iSpeedBytesIndex]) + while (nowSlot > m_speedTime[m_speedBytesIndex]) { //record bytes in next slot - m_iSpeedBytesIndex++; - if (m_iSpeedBytesIndex >= SPEEDMETER_SLOTS) + m_speedBytesIndex++; + if (m_speedBytesIndex >= SPEEDMETER_SLOTS) { - m_iSpeedBytesIndex = 0; + m_speedBytesIndex = 0; } //Adjust counters with outgoing information. - m_iSpeedTotalBytes = m_iSpeedTotalBytes - (long long)m_iSpeedBytes[m_iSpeedBytesIndex]; + m_speedTotalBytes = m_speedTotalBytes - (long long)m_speedBytes[m_speedBytesIndex]; //Note we should really use the start time of the next slot //but its easier to just use the outgoing slot time. This //will result in a small error. - m_iSpeedStartTime = m_iSpeedTime[m_iSpeedBytesIndex]; + m_speedStartTime = m_speedTime[m_speedBytesIndex]; //Now reset. - m_iSpeedBytes[m_iSpeedBytesIndex] = 0; - m_iSpeedTime[m_iSpeedBytesIndex] = iNowSlot; + m_speedBytes[m_speedBytesIndex] = 0; + m_speedTime[m_speedBytesIndex] = nowSlot; } // Once per second recalculate summary field "m_iSpeedTotalBytes" to recover from possible synchronisation errors - if (tCurTime > m_tSpeedCorrection) + if (curTime > m_speedCorrection) { - long long iSpeedTotalBytes = 0; + long long speedTotalBytes = 0; for (int i = 0; i < SPEEDMETER_SLOTS; i++) { - iSpeedTotalBytes += m_iSpeedBytes[i]; + speedTotalBytes += m_speedBytes[i]; } - m_iSpeedTotalBytes = iSpeedTotalBytes; - m_tSpeedCorrection = tCurTime; + m_speedTotalBytes = speedTotalBytes; + m_speedCorrection = curTime; } - if (m_iSpeedTotalBytes == 0) + if (m_speedTotalBytes == 0) { - m_iSpeedStartTime = iNowSlot; + m_speedStartTime = nowSlot; } - m_iSpeedBytes[m_iSpeedBytesIndex] += iBytes; - m_iSpeedTotalBytes += iBytes; - m_iAllBytes += iBytes; + m_speedBytes[m_speedBytesIndex] += bytes; + m_speedTotalBytes += bytes; + m_allBytes += bytes; if (g_pOptions->GetAccurateRate()) { - m_mutexSpeed.Unlock(); + m_speedMutex.Unlock(); } } void StatMeter::ResetSpeedStat() { - time_t tCurTime = time(NULL); - m_iSpeedStartTime = (int)tCurTime / SPEEDMETER_SLOTSIZE; + time_t curTime = time(NULL); + m_speedStartTime = (int)curTime / SPEEDMETER_SLOTSIZE; for (int i = 0; i < SPEEDMETER_SLOTS; i++) { - m_iSpeedBytes[i] = 0; - m_iSpeedTime[i] = m_iSpeedStartTime; + m_speedBytes[i] = 0; + m_speedTime[i] = m_speedStartTime; } - m_iSpeedBytesIndex = 0; - m_iSpeedTotalBytes = 0; - m_tSpeedCorrection = tCurTime; - m_tCurSecTime = 0; - m_iCurSecBytes = 0; + m_speedBytesIndex = 0; + m_speedTotalBytes = 0; + m_speedCorrection = curTime; + m_curSecTime = 0; + m_curSecBytes = 0; } void StatMeter::LogDebugInfo() { info(" ---------- SpeedMeter"); - int iSpeed = CalcCurrentDownloadSpeed() / 1024; - int iTimeDiff = (int)time(NULL) - m_iSpeedStartTime * SPEEDMETER_SLOTSIZE; - info(" Speed: %i", iSpeed); - info(" SpeedStartTime: %i", m_iSpeedStartTime); - info(" SpeedTotalBytes: %i", m_iSpeedTotalBytes); - info(" SpeedBytesIndex: %i", m_iSpeedBytesIndex); - info(" AllBytes: %i", m_iAllBytes); + int speed = CalcCurrentDownloadSpeed() / 1024; + int timeDiff = (int)time(NULL) - m_speedStartTime * SPEEDMETER_SLOTSIZE; + info(" Speed: %i", speed); + info(" SpeedStartTime: %i", m_speedStartTime); + info(" SpeedTotalBytes: %i", m_speedTotalBytes); + info(" SpeedBytesIndex: %i", m_speedBytesIndex); + info(" AllBytes: %i", m_allBytes); info(" Time: %i", (int)time(NULL)); - info(" TimeDiff: %i", iTimeDiff); + info(" TimeDiff: %i", timeDiff); for (int i=0; i < SPEEDMETER_SLOTS; i++) { - info(" Bytes[%i]: %i, Time[%i]: %i", i, m_iSpeedBytes[i], i, m_iSpeedTime[i]); + info(" Bytes[%i]: %i, Time[%i]: %i", i, m_speedBytes[i], i, m_speedTime[i]); } - m_mutexVolume.Lock(); + m_volumeMutex.Lock(); int index = 0; - for (ServerVolumes::iterator it = m_ServerVolumes.begin(); it != m_ServerVolumes.end(); it++, index++) + for (ServerVolumes::iterator it = m_serverVolumes.begin(); it != m_serverVolumes.end(); it++, index++) { - ServerVolume* pServerVolume = *it; + ServerVolume* serverVolume = *it; info(" ServerVolume %i", index); - pServerVolume->LogDebugInfo(); + serverVolume->LogDebugInfo(); } - m_mutexVolume.Unlock(); + m_volumeMutex.Unlock(); } -void StatMeter::AddServerData(int iBytes, int iServerID) +void StatMeter::AddServerData(int bytes, int serverId) { - if (iBytes == 0) + if (bytes == 0) { return; } - m_mutexVolume.Lock(); - m_ServerVolumes[0]->AddData(iBytes); - m_ServerVolumes[iServerID]->AddData(iBytes); - m_bStatChanged = true; - m_mutexVolume.Unlock(); + m_volumeMutex.Lock(); + m_serverVolumes[0]->AddData(bytes); + m_serverVolumes[serverId]->AddData(bytes); + m_statChanged = true; + m_volumeMutex.Unlock(); } ServerVolumes* StatMeter::LockServerVolumes() { - m_mutexVolume.Lock(); + m_volumeMutex.Lock(); // update slots - for (ServerVolumes::iterator it = m_ServerVolumes.begin(); it != m_ServerVolumes.end(); it++) + for (ServerVolumes::iterator it = m_serverVolumes.begin(); it != m_serverVolumes.end(); it++) { - ServerVolume* pServerVolume = *it; - pServerVolume->AddData(0); + ServerVolume* serverVolume = *it; + serverVolume->AddData(0); } - return &m_ServerVolumes; + return &m_serverVolumes; } void StatMeter::UnlockServerVolumes() { - m_mutexVolume.Unlock(); + m_volumeMutex.Unlock(); } void StatMeter::Save() @@ -525,25 +525,25 @@ void StatMeter::Save() return; } - m_mutexVolume.Lock(); - g_pDiskState->SaveStats(g_pServerPool->GetServers(), &m_ServerVolumes); - m_bStatChanged = false; - m_mutexVolume.Unlock(); + m_volumeMutex.Lock(); + g_pDiskState->SaveStats(g_pServerPool->GetServers(), &m_serverVolumes); + m_statChanged = false; + m_volumeMutex.Unlock(); } -bool StatMeter::Load(bool* pPerfectServerMatch) +bool StatMeter::Load(bool* perfectServerMatch) { - m_mutexVolume.Lock(); + m_volumeMutex.Lock(); - bool bOK = g_pDiskState->LoadStats(g_pServerPool->GetServers(), &m_ServerVolumes, pPerfectServerMatch); + bool ok = g_pDiskState->LoadStats(g_pServerPool->GetServers(), &m_serverVolumes, perfectServerMatch); - for (ServerVolumes::iterator it = m_ServerVolumes.begin(); it != m_ServerVolumes.end(); it++) + for (ServerVolumes::iterator it = m_serverVolumes.begin(); it != m_serverVolumes.end(); it++) { - ServerVolume* pServerVolume = *it; - pServerVolume->CalcSlots(pServerVolume->GetDataTime() + g_pOptions->GetLocalTimeOffset()); + ServerVolume* serverVolume = *it; + serverVolume->CalcSlots(serverVolume->GetDataTime() + g_pOptions->GetLocalTimeOffset()); } - m_mutexVolume.Unlock(); + m_volumeMutex.Unlock(); - return bOK; + return ok; } diff --git a/daemon/nntp/StatMeter.h b/daemon/nntp/StatMeter.h index 38104c25..2794b565 100644 --- a/daemon/nntp/StatMeter.h +++ b/daemon/nntp/StatMeter.h @@ -38,43 +38,43 @@ public: typedef std::vector VolumeArray; private: - VolumeArray m_BytesPerSeconds; - VolumeArray m_BytesPerMinutes; - VolumeArray m_BytesPerHours; - VolumeArray m_BytesPerDays; - int m_iFirstDay; - long long m_lTotalBytes; - long long m_lCustomBytes; - time_t m_tDataTime; - time_t m_tCustomTime; - int m_iSecSlot; - int m_iMinSlot; - int m_iHourSlot; - int m_iDaySlot; + VolumeArray m_bytesPerSeconds; + VolumeArray m_bytesPerMinutes; + VolumeArray m_bytesPerHours; + VolumeArray m_bytesPerDays; + int m_firstDay; + long long m_totalBytes; + long long m_customBytes; + time_t m_dataTime; + time_t m_customTime; + int m_secSlot; + int m_minSlot; + int m_hourSlot; + int m_daySlot; public: ServerVolume(); - VolumeArray* BytesPerSeconds() { return &m_BytesPerSeconds; } - VolumeArray* BytesPerMinutes() { return &m_BytesPerMinutes; } - VolumeArray* BytesPerHours() { return &m_BytesPerHours; } - VolumeArray* BytesPerDays() { return &m_BytesPerDays; } - void SetFirstDay(int iFirstDay) { m_iFirstDay = iFirstDay; } - int GetFirstDay() { return m_iFirstDay; } - void SetTotalBytes(long long lTotalBytes) { m_lTotalBytes = lTotalBytes; } - long long GetTotalBytes() { return m_lTotalBytes; } - void SetCustomBytes(long long lCustomBytes) { m_lCustomBytes = lCustomBytes; } - long long GetCustomBytes() { return m_lCustomBytes; } - int GetSecSlot() { return m_iSecSlot; } - int GetMinSlot() { return m_iMinSlot; } - int GetHourSlot() { return m_iHourSlot; } - int GetDaySlot() { return m_iDaySlot; } - time_t GetDataTime() { return m_tDataTime; } - void SetDataTime(time_t tDataTime) { m_tDataTime = tDataTime; } - time_t GetCustomTime() { return m_tCustomTime; } - void SetCustomTime(time_t tCustomTime) { m_tCustomTime = tCustomTime; } + VolumeArray* BytesPerSeconds() { return &m_bytesPerSeconds; } + VolumeArray* BytesPerMinutes() { return &m_bytesPerMinutes; } + VolumeArray* BytesPerHours() { return &m_bytesPerHours; } + VolumeArray* BytesPerDays() { return &m_bytesPerDays; } + void SetFirstDay(int firstDay) { m_firstDay = firstDay; } + int GetFirstDay() { return m_firstDay; } + void SetTotalBytes(long long totalBytes) { m_totalBytes = totalBytes; } + long long GetTotalBytes() { return m_totalBytes; } + void SetCustomBytes(long long customBytes) { m_customBytes = customBytes; } + long long GetCustomBytes() { return m_customBytes; } + int GetSecSlot() { return m_secSlot; } + int GetMinSlot() { return m_minSlot; } + int GetHourSlot() { return m_hourSlot; } + int GetDaySlot() { return m_daySlot; } + time_t GetDataTime() { return m_dataTime; } + void SetDataTime(time_t dataTime) { m_dataTime = dataTime; } + time_t GetCustomTime() { return m_customTime; } + void SetCustomTime(time_t customTime) { m_customTime = customTime; } - void AddData(int iBytes); - void CalcSlots(time_t tLocCurTime); + void AddData(int bytes); + void CalcSlots(time_t locCurTime); void ResetCustom(); void LogDebugInfo(); }; @@ -87,30 +87,30 @@ private: // speed meter static const int SPEEDMETER_SLOTS = 30; static const int SPEEDMETER_SLOTSIZE = 1; //Split elapsed time into this number of secs. - int m_iSpeedBytes[SPEEDMETER_SLOTS]; - long long m_iSpeedTotalBytes; - int m_iSpeedTime[SPEEDMETER_SLOTS]; - int m_iSpeedStartTime; - time_t m_tSpeedCorrection; - int m_iSpeedBytesIndex; - int m_iCurSecBytes; - time_t m_tCurSecTime; - Mutex m_mutexSpeed; + int m_speedBytes[SPEEDMETER_SLOTS]; + long long m_speedTotalBytes; + int m_speedTime[SPEEDMETER_SLOTS]; + int m_speedStartTime; + time_t m_speedCorrection; + int m_speedBytesIndex; + int m_curSecBytes; + time_t m_curSecTime; + Mutex m_speedMutex; // time - long long m_iAllBytes; - time_t m_tStartServer; - time_t m_tLastCheck; - time_t m_tLastTimeOffset; - time_t m_tStartDownload; - time_t m_tPausedFrom; - bool m_bStandBy; - Mutex m_mutexStat; + long long m_allBytes; + time_t m_startServer; + time_t m_lastCheck; + time_t m_lastTimeOffset; + time_t m_startDownload; + time_t m_pausedFrom; + bool m_standBy; + Mutex m_statMutex; // data volume - bool m_bStatChanged; - ServerVolumes m_ServerVolumes; - Mutex m_mutexVolume; + bool m_statChanged; + ServerVolumes m_serverVolumes; + Mutex m_volumeMutex; void ResetSpeedStat(); void AdjustTimeOffset(); @@ -124,16 +124,16 @@ public: void Init(); int CalcCurrentDownloadSpeed(); int CalcMomentaryDownloadSpeed(); - void AddSpeedReading(int iBytes); - void AddServerData(int iBytes, int iServerID); - void CalcTotalStat(int* iUpTimeSec, int* iDnTimeSec, long long* iAllBytes, bool* bStandBy); - bool GetStandBy() { return m_bStandBy; } + void AddSpeedReading(int bytes); + void AddServerData(int bytes, int serverId); + void CalcTotalStat(int* upTimeSec, int* dnTimeSec, long long* allBytes, bool* standBy); + bool GetStandBy() { return m_standBy; } void IntervalCheck(); - void EnterLeaveStandBy(bool bEnter); + void EnterLeaveStandBy(bool enter); ServerVolumes* LockServerVolumes(); void UnlockServerVolumes(); void Save(); - bool Load(bool* pPerfectServerMatch); + bool Load(bool* perfectServerMatch); }; extern StatMeter* g_pStatMeter; diff --git a/daemon/postprocess/Cleanup.cpp b/daemon/postprocess/Cleanup.cpp index 6ef26ed8..176e7e55 100644 --- a/daemon/postprocess/Cleanup.cpp +++ b/daemon/postprocess/Cleanup.cpp @@ -47,15 +47,15 @@ #include "ParParser.h" #include "Options.h" -void MoveController::StartJob(PostInfo* pPostInfo) +void MoveController::StartJob(PostInfo* postInfo) { - MoveController* pMoveController = new MoveController(); - pMoveController->m_pPostInfo = pPostInfo; - pMoveController->SetAutoDestroy(false); + MoveController* moveController = new MoveController(); + moveController->m_postInfo = postInfo; + moveController->SetAutoDestroy(false); - pPostInfo->SetPostThread(pMoveController); + postInfo->SetPostThread(moveController); - pMoveController->Start(); + moveController->Start(); } void MoveController::Run() @@ -63,109 +63,109 @@ void MoveController::Run() // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); - char szNZBName[1024]; - strncpy(szNZBName, m_pPostInfo->GetNZBInfo()->GetName(), 1024); - szNZBName[1024-1] = '\0'; + char nzbName[1024]; + strncpy(nzbName, m_postInfo->GetNZBInfo()->GetName(), 1024); + nzbName[1024-1] = '\0'; - char szInfoName[1024]; - snprintf(szInfoName, 1024, "move for %s", m_pPostInfo->GetNZBInfo()->GetName()); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "move for %s", m_postInfo->GetNZBInfo()->GetName()); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - strncpy(m_szInterDir, m_pPostInfo->GetNZBInfo()->GetDestDir(), 1024); - m_szInterDir[1024-1] = '\0'; + strncpy(m_interDir, m_postInfo->GetNZBInfo()->GetDestDir(), 1024); + m_interDir[1024-1] = '\0'; - m_pPostInfo->GetNZBInfo()->BuildFinalDirName(m_szDestDir, 1024); - m_szDestDir[1024-1] = '\0'; + m_postInfo->GetNZBInfo()->BuildFinalDirName(m_destDir, 1024); + m_destDir[1024-1] = '\0'; DownloadQueue::Unlock(); - PrintMessage(Message::mkInfo, "Moving completed files for %s", szNZBName); + PrintMessage(Message::mkInfo, "Moving completed files for %s", nzbName); - bool bOK = MoveFiles(); + bool ok = MoveFiles(); - szInfoName[0] = 'M'; // uppercase + infoName[0] = 'M'; // uppercase - if (bOK) + if (ok) { - PrintMessage(Message::mkInfo, "%s successful", szInfoName); + PrintMessage(Message::mkInfo, "%s successful", infoName); // save new dest dir DownloadQueue::Lock(); - m_pPostInfo->GetNZBInfo()->SetDestDir(m_szDestDir); - m_pPostInfo->GetNZBInfo()->SetMoveStatus(NZBInfo::msSuccess); + m_postInfo->GetNZBInfo()->SetDestDir(m_destDir); + m_postInfo->GetNZBInfo()->SetMoveStatus(NZBInfo::msSuccess); DownloadQueue::Unlock(); } else { - PrintMessage(Message::mkError, "%s failed", szInfoName); - m_pPostInfo->GetNZBInfo()->SetMoveStatus(NZBInfo::msFailure); + PrintMessage(Message::mkError, "%s failed", infoName); + m_postInfo->GetNZBInfo()->SetMoveStatus(NZBInfo::msFailure); } - m_pPostInfo->SetStage(PostInfo::ptQueued); - m_pPostInfo->SetWorking(false); + m_postInfo->SetStage(PostInfo::ptQueued); + m_postInfo->SetWorking(false); } bool MoveController::MoveFiles() { - char szErrBuf[1024]; - if (!Util::ForceDirectories(m_szDestDir, szErrBuf, sizeof(szErrBuf))) + char errBuf[1024]; + if (!Util::ForceDirectories(m_destDir, errBuf, sizeof(errBuf))) { - PrintMessage(Message::mkError, "Could not create directory %s: %s", m_szDestDir, szErrBuf); + PrintMessage(Message::mkError, "Could not create directory %s: %s", m_destDir, errBuf); return false; } - bool bOK = true; - DirBrowser dir(m_szInterDir); + bool ok = true; + DirBrowser dir(m_interDir); while (const char* filename = dir.Next()) { if (strcmp(filename, ".") && strcmp(filename, "..")) { - char szSrcFile[1024]; - snprintf(szSrcFile, 1024, "%s%c%s", m_szInterDir, PATH_SEPARATOR, filename); - szSrcFile[1024-1] = '\0'; + char srcFile[1024]; + snprintf(srcFile, 1024, "%s%c%s", m_interDir, PATH_SEPARATOR, filename); + srcFile[1024-1] = '\0'; - char szDstFile[1024]; - Util::MakeUniqueFilename(szDstFile, 1024, m_szDestDir, filename); + char dstFile[1024]; + Util::MakeUniqueFilename(dstFile, 1024, m_destDir, filename); - bool bHiddenFile = filename[0] == '.'; + bool hiddenFile = filename[0] == '.'; - if (!bHiddenFile) + if (!hiddenFile) { - PrintMessage(Message::mkInfo, "Moving file %s to %s", Util::BaseFileName(szSrcFile), m_szDestDir); + PrintMessage(Message::mkInfo, "Moving file %s to %s", Util::BaseFileName(srcFile), m_destDir); } - if (!Util::MoveFile(szSrcFile, szDstFile) && !bHiddenFile) + if (!Util::MoveFile(srcFile, dstFile) && !hiddenFile) { - char szErrBuf[256]; - PrintMessage(Message::mkError, "Could not move file %s to %s: %s", szSrcFile, szDstFile, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); - bOK = false; + char errBuf[256]; + PrintMessage(Message::mkError, "Could not move file %s to %s: %s", srcFile, dstFile, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); + ok = false; } } } - if (bOK && !Util::DeleteDirectoryWithContent(m_szInterDir, szErrBuf, sizeof(szErrBuf))) + if (ok && !Util::DeleteDirectoryWithContent(m_interDir, errBuf, sizeof(errBuf))) { - PrintMessage(Message::mkWarning, "Could not delete intermediate directory %s: %s", m_szInterDir, szErrBuf); + PrintMessage(Message::mkWarning, "Could not delete intermediate directory %s: %s", m_interDir, errBuf); } - return bOK; + return ok; } -void MoveController::AddMessage(Message::EKind eKind, const char* szText) +void MoveController::AddMessage(Message::EKind kind, const char* text) { - m_pPostInfo->GetNZBInfo()->AddMessage(eKind, szText); + m_postInfo->GetNZBInfo()->AddMessage(kind, text); } -void CleanupController::StartJob(PostInfo* pPostInfo) +void CleanupController::StartJob(PostInfo* postInfo) { - CleanupController* pCleanupController = new CleanupController(); - pCleanupController->m_pPostInfo = pPostInfo; - pCleanupController->SetAutoDestroy(false); + CleanupController* cleanupController = new CleanupController(); + cleanupController->m_postInfo = postInfo; + cleanupController->SetAutoDestroy(false); - pPostInfo->SetPostThread(pCleanupController); + postInfo->SetPostThread(cleanupController); - pCleanupController->Start(); + cleanupController->Start(); } void CleanupController::Run() @@ -173,106 +173,106 @@ void CleanupController::Run() // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); - char szNZBName[1024]; - strncpy(szNZBName, m_pPostInfo->GetNZBInfo()->GetName(), 1024); - szNZBName[1024-1] = '\0'; + char nzbName[1024]; + strncpy(nzbName, m_postInfo->GetNZBInfo()->GetName(), 1024); + nzbName[1024-1] = '\0'; - char szInfoName[1024]; - snprintf(szInfoName, 1024, "cleanup for %s", m_pPostInfo->GetNZBInfo()->GetName()); - szInfoName[1024-1] = '\0'; - SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "cleanup for %s", m_postInfo->GetNZBInfo()->GetName()); + infoName[1024-1] = '\0'; + SetInfoName(infoName); - strncpy(m_szDestDir, m_pPostInfo->GetNZBInfo()->GetDestDir(), 1024); - m_szDestDir[1024-1] = '\0'; + strncpy(m_destDir, m_postInfo->GetNZBInfo()->GetDestDir(), 1024); + m_destDir[1024-1] = '\0'; - bool bInterDir = strlen(g_pOptions->GetInterDir()) > 0 && - !strncmp(m_szDestDir, g_pOptions->GetInterDir(), strlen(g_pOptions->GetInterDir())); - if (bInterDir) + bool interDir = strlen(g_pOptions->GetInterDir()) > 0 && + !strncmp(m_destDir, g_pOptions->GetInterDir(), strlen(g_pOptions->GetInterDir())); + if (interDir) { - m_pPostInfo->GetNZBInfo()->BuildFinalDirName(m_szFinalDir, 1024); - m_szFinalDir[1024-1] = '\0'; + m_postInfo->GetNZBInfo()->BuildFinalDirName(m_finalDir, 1024); + m_finalDir[1024-1] = '\0'; } else { - m_szFinalDir[0] = '\0'; + m_finalDir[0] = '\0'; } DownloadQueue::Unlock(); - PrintMessage(Message::mkInfo, "Cleaning up %s", szNZBName); + PrintMessage(Message::mkInfo, "Cleaning up %s", nzbName); - bool bDeleted = false; - bool bOK = Cleanup(m_szDestDir, &bDeleted); + bool deleted = false; + bool ok = Cleanup(m_destDir, &deleted); - if (bOK && m_szFinalDir[0] != '\0') + if (ok && m_finalDir[0] != '\0') { - bool bDeleted2 = false; - bOK = Cleanup(m_szFinalDir, &bDeleted2); - bDeleted = bDeleted || bDeleted2; + bool deleted2 = false; + ok = Cleanup(m_finalDir, &deleted2); + deleted = deleted || deleted2; } - szInfoName[0] = 'C'; // uppercase + infoName[0] = 'C'; // uppercase - if (bOK && bDeleted) + if (ok && deleted) { - PrintMessage(Message::mkInfo, "%s successful", szInfoName); - m_pPostInfo->GetNZBInfo()->SetCleanupStatus(NZBInfo::csSuccess); + PrintMessage(Message::mkInfo, "%s successful", infoName); + m_postInfo->GetNZBInfo()->SetCleanupStatus(NZBInfo::csSuccess); } - else if (bOK) + else if (ok) { - PrintMessage(Message::mkInfo, "Nothing to cleanup for %s", szNZBName); - m_pPostInfo->GetNZBInfo()->SetCleanupStatus(NZBInfo::csSuccess); + PrintMessage(Message::mkInfo, "Nothing to cleanup for %s", nzbName); + m_postInfo->GetNZBInfo()->SetCleanupStatus(NZBInfo::csSuccess); } else { - PrintMessage(Message::mkError, "%s failed", szInfoName); - m_pPostInfo->GetNZBInfo()->SetCleanupStatus(NZBInfo::csFailure); + PrintMessage(Message::mkError, "%s failed", infoName); + m_postInfo->GetNZBInfo()->SetCleanupStatus(NZBInfo::csFailure); } - m_pPostInfo->SetStage(PostInfo::ptQueued); - m_pPostInfo->SetWorking(false); + m_postInfo->SetStage(PostInfo::ptQueued); + m_postInfo->SetWorking(false); } -bool CleanupController::Cleanup(const char* szDestDir, bool *bDeleted) +bool CleanupController::Cleanup(const char* destDir, bool *deleted) { - *bDeleted = false; - bool bOK = true; + *deleted = false; + bool ok = true; - DirBrowser dir(szDestDir); + DirBrowser dir(destDir); while (const char* filename = dir.Next()) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", szDestDir, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", destDir, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - bool bIsDir = Util::DirectoryExists(szFullFilename); + bool isDir = Util::DirectoryExists(fullFilename); - if (strcmp(filename, ".") && strcmp(filename, "..") && bIsDir) + if (strcmp(filename, ".") && strcmp(filename, "..") && isDir) { - bOK &= Cleanup(szFullFilename, bDeleted); + ok &= Cleanup(fullFilename, deleted); } // check file extension - bool bDeleteIt = Util::MatchFileExt(filename, g_pOptions->GetExtCleanupDisk(), ",;") && !bIsDir; + bool deleteIt = Util::MatchFileExt(filename, g_pOptions->GetExtCleanupDisk(), ",;") && !isDir; - if (bDeleteIt) + if (deleteIt) { PrintMessage(Message::mkInfo, "Deleting file %s", filename); - if (remove(szFullFilename) != 0) + if (remove(fullFilename) != 0) { - char szErrBuf[256]; - PrintMessage(Message::mkError, "Could not delete file %s: %s", szFullFilename, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); - bOK = false; + char errBuf[256]; + PrintMessage(Message::mkError, "Could not delete file %s: %s", fullFilename, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); + ok = false; } - *bDeleted = true; + *deleted = true; } } - return bOK; + return ok; } -void CleanupController::AddMessage(Message::EKind eKind, const char* szText) +void CleanupController::AddMessage(Message::EKind kind, const char* text) { - m_pPostInfo->GetNZBInfo()->AddMessage(eKind, szText); + m_postInfo->GetNZBInfo()->AddMessage(kind, text); } diff --git a/daemon/postprocess/Cleanup.h b/daemon/postprocess/Cleanup.h index c041d605..64d7b246 100644 --- a/daemon/postprocess/Cleanup.h +++ b/daemon/postprocess/Cleanup.h @@ -34,35 +34,35 @@ class MoveController : public Thread, public ScriptController { private: - PostInfo* m_pPostInfo; - char m_szInterDir[1024]; - char m_szDestDir[1024]; + PostInfo* m_postInfo; + char m_interDir[1024]; + char m_destDir[1024]; bool MoveFiles(); protected: - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void AddMessage(Message::EKind kind, const char* text); public: virtual void Run(); - static void StartJob(PostInfo* pPostInfo); + static void StartJob(PostInfo* postInfo); }; class CleanupController : public Thread, public ScriptController { private: - PostInfo* m_pPostInfo; - char m_szDestDir[1024]; - char m_szFinalDir[1024]; + PostInfo* m_postInfo; + char m_destDir[1024]; + char m_finalDir[1024]; - bool Cleanup(const char* szDestDir, bool *bDeleted); + bool Cleanup(const char* destDir, bool *deleted); protected: - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void AddMessage(Message::EKind kind, const char* text); public: virtual void Run(); - static void StartJob(PostInfo* pPostInfo); + static void StartJob(PostInfo* postInfo); }; #endif diff --git a/daemon/postprocess/DupeMatcher.cpp b/daemon/postprocess/DupeMatcher.cpp index ee9fd682..b83d8a80 100644 --- a/daemon/postprocess/DupeMatcher.cpp +++ b/daemon/postprocess/DupeMatcher.cpp @@ -51,53 +51,53 @@ class RarLister : public Thread, public ScriptController { private: - DupeMatcher* m_pOwner; - long long m_lMaxSize; - bool m_bCompressed; - bool m_bLastSizeMax; - long long m_lExpectedSize; - char* m_szFilenameBuf; - int m_iFilenameBufLen; - char m_szLastFilename[1024]; + DupeMatcher* m_owner; + long long m_maxSize; + bool m_compressed; + bool m_lastSizeMax; + long long m_expectedSize; + char* m_filenameBuf; + int m_filenameBufLen; + char m_lastFilename[1024]; protected: - virtual void AddMessage(Message::EKind eKind, const char* szText); + virtual void AddMessage(Message::EKind kind, const char* text); public: virtual void Run(); - static bool FindLargestFile(DupeMatcher* pOwner, const char* szDirectory, - char* szFilenameBuf, int iFilenameBufLen, long long lExpectedSize, - int iTimeoutSec, long long* pMaxSize, bool* pCompressed); + static bool FindLargestFile(DupeMatcher* owner, const char* directory, + char* filenameBuf, int filenameBufLen, long long expectedSize, + int timeoutSec, long long* maxSize, bool* compressed); }; -bool RarLister::FindLargestFile(DupeMatcher* pOwner, const char* szDirectory, - char* szFilenameBuf, int iFilenameBufLen, long long lExpectedSize, - int iTimeoutSec, long long* pMaxSize, bool* pCompressed) +bool RarLister::FindLargestFile(DupeMatcher* owner, const char* directory, + char* filenameBuf, int filenameBufLen, long long expectedSize, + int timeoutSec, long long* maxSize, bool* compressed) { RarLister unrar; - unrar.m_pOwner = pOwner; - unrar.m_lExpectedSize = lExpectedSize; - unrar.m_lMaxSize = -1; - unrar.m_bCompressed = false; - unrar.m_bLastSizeMax = false; - unrar.m_szFilenameBuf = szFilenameBuf; - unrar.m_iFilenameBufLen = iFilenameBufLen; + unrar.m_owner = owner; + unrar.m_expectedSize = expectedSize; + unrar.m_maxSize = -1; + unrar.m_compressed = false; + unrar.m_lastSizeMax = false; + unrar.m_filenameBuf = filenameBuf; + unrar.m_filenameBufLen = filenameBufLen; - char** pCmdArgs = NULL; - if (!Util::SplitCommandLine(g_pOptions->GetUnrarCmd(), &pCmdArgs)) + char** cmdArgs = NULL; + if (!Util::SplitCommandLine(g_pOptions->GetUnrarCmd(), &cmdArgs)) { return false; } - const char* szUnrarPath = *pCmdArgs; - unrar.SetScript(szUnrarPath); + const char* unrarPath = *cmdArgs; + unrar.SetScript(unrarPath); - const char* szArgs[4]; - szArgs[0] = szUnrarPath; - szArgs[1] = "lt"; - szArgs[2] = "*.rar"; - szArgs[3] = NULL; - unrar.SetArgs(szArgs, false); - unrar.SetWorkingDir(szDirectory); + const char* args[4]; + args[0] = unrarPath; + args[1] = "lt"; + args[2] = "*.rar"; + args[3] = NULL; + unrar.SetArgs(args, false); + unrar.SetWorkingDir(directory); time_t curTime = time(NULL); @@ -105,7 +105,7 @@ bool RarLister::FindLargestFile(DupeMatcher* pOwner, const char* szDirectory, // wait up to iTimeoutSec for unrar output while (unrar.IsRunning() && - curTime + iTimeoutSec > time(NULL) && + curTime + timeoutSec > time(NULL) && curTime >= time(NULL)) // in a case clock was changed { usleep(200 * 1000); @@ -122,14 +122,14 @@ bool RarLister::FindLargestFile(DupeMatcher* pOwner, const char* szDirectory, usleep(200 * 1000); } - for (char** szArgPtr = pCmdArgs; *szArgPtr; szArgPtr++) + for (char** argPtr = cmdArgs; *argPtr; argPtr++) { - free(*szArgPtr); + free(*argPtr); } - free(pCmdArgs); + free(cmdArgs); - *pMaxSize = unrar.m_lMaxSize; - *pCompressed = unrar.m_bCompressed; + *maxSize = unrar.m_maxSize; + *compressed = unrar.m_compressed; return true; } @@ -139,36 +139,36 @@ void RarLister::Run() Execute(); } -void RarLister::AddMessage(Message::EKind eKind, const char* szText) +void RarLister::AddMessage(Message::EKind kind, const char* text) { - if (!strncasecmp(szText, "Archive: ", 9)) + if (!strncasecmp(text, "Archive: ", 9)) { - m_pOwner->PrintMessage(Message::mkDetail, "Reading file %s", szText + 9); + m_owner->PrintMessage(Message::mkDetail, "Reading file %s", text + 9); } - else if (!strncasecmp(szText, " Name: ", 14)) + else if (!strncasecmp(text, " Name: ", 14)) { - strncpy(m_szLastFilename, szText + 14, sizeof(m_szLastFilename)); - m_szLastFilename[sizeof(m_szLastFilename)-1] = '\0'; + strncpy(m_lastFilename, text + 14, sizeof(m_lastFilename)); + m_lastFilename[sizeof(m_lastFilename)-1] = '\0'; } - else if (!strncasecmp(szText, " Size: ", 14)) + else if (!strncasecmp(text, " Size: ", 14)) { - m_bLastSizeMax = false; - long long lSize = atoll(szText + 14); - if (lSize > m_lMaxSize) + m_lastSizeMax = false; + long long size = atoll(text + 14); + if (size > m_maxSize) { - m_lMaxSize = lSize; - m_bLastSizeMax = true; - strncpy(m_szFilenameBuf, m_szLastFilename, m_iFilenameBufLen); - m_szFilenameBuf[m_iFilenameBufLen-1] = '\0'; + m_maxSize = size; + m_lastSizeMax = true; + strncpy(m_filenameBuf, m_lastFilename, m_filenameBufLen); + m_filenameBuf[m_filenameBufLen-1] = '\0'; } return; } - if (m_bLastSizeMax && !strncasecmp(szText, " Compression: ", 14)) + if (m_lastSizeMax && !strncasecmp(text, " Compression: ", 14)) { - m_bCompressed = !strstr(szText, " -m0"); - if (m_lMaxSize > m_lExpectedSize || - DupeMatcher::SizeDiffOK(m_lMaxSize, m_lExpectedSize, 20)) + m_compressed = !strstr(text, " -m0"); + if (m_maxSize > m_expectedSize || + DupeMatcher::SizeDiffOK(m_maxSize, m_expectedSize, 20)) { // alread found the largest file, aborting unrar Terminate(); @@ -177,82 +177,82 @@ void RarLister::AddMessage(Message::EKind eKind, const char* szText) } -DupeMatcher::DupeMatcher(const char* szDestDir, long long lExpectedSize) +DupeMatcher::DupeMatcher(const char* destDir, long long expectedSize) { - m_szDestDir = strdup(szDestDir); - m_lExpectedSize = lExpectedSize; - m_lMaxSize = -1; - m_bCompressed = false; + m_destDir = strdup(destDir); + m_expectedSize = expectedSize; + m_maxSize = -1; + m_compressed = false; } DupeMatcher::~DupeMatcher() { - free(m_szDestDir); + free(m_destDir); } -bool DupeMatcher::SizeDiffOK(long long lSize1, long long lSize2, int iMaxDiffPercent) +bool DupeMatcher::SizeDiffOK(long long size1, long long size2, int maxDiffPercent) { - if (lSize1 == 0 || lSize2 == 0) + if (size1 == 0 || size2 == 0) { return false; } - long long lDiff = lSize1 - lSize2; - lDiff = lDiff > 0 ? lDiff : -lDiff; - long long lMax = lSize1 > lSize2 ? lSize1 : lSize2; - int lDiffPercent = (int)(lDiff * 100 / lMax); - return lDiffPercent < iMaxDiffPercent; + long long diff = size1 - size2; + diff = diff > 0 ? diff : -diff; + long long max = size1 > size2 ? size1 : size2; + int diffPercent = (int)(diff * 100 / max); + return diffPercent < maxDiffPercent; } bool DupeMatcher::Prepare() { - char szFilename[1024]; - FindLargestFile(m_szDestDir, szFilename, sizeof(szFilename), &m_lMaxSize, &m_bCompressed); - bool bSizeOK = SizeDiffOK(m_lMaxSize, m_lExpectedSize, 20); + char filename[1024]; + FindLargestFile(m_destDir, filename, sizeof(filename), &m_maxSize, &m_compressed); + bool sizeOK = SizeDiffOK(m_maxSize, m_expectedSize, 20); PrintMessage(Message::mkDetail, "Found main file %s with size %lli bytes%s", - szFilename, m_lMaxSize, bSizeOK ? "" : ", size mismatch"); - return bSizeOK; + filename, m_maxSize, sizeOK ? "" : ", size mismatch"); + return sizeOK; } -bool DupeMatcher::MatchDupeContent(const char* szDupeDir) +bool DupeMatcher::MatchDupeContent(const char* dupeDir) { - long long lDupeMaxSize = 0; - bool lDupeCompressed = false; - char szFilename[1024]; - FindLargestFile(szDupeDir, szFilename, sizeof(szFilename), &lDupeMaxSize, &lDupeCompressed); - bool bOK = lDupeMaxSize == m_lMaxSize && lDupeCompressed == m_bCompressed; + long long dupeMaxSize = 0; + bool dupeCompressed = false; + char filename[1024]; + FindLargestFile(dupeDir, filename, sizeof(filename), &dupeMaxSize, &dupeCompressed); + bool ok = dupeMaxSize == m_maxSize && dupeCompressed == m_compressed; PrintMessage(Message::mkDetail, "Found main file %s with size %lli bytes%s", - szFilename, m_lMaxSize, bOK ? "" : ", size mismatch"); - return bOK; + filename, m_maxSize, ok ? "" : ", size mismatch"); + return ok; } -void DupeMatcher::FindLargestFile(const char* szDirectory, char* szFilenameBuf, int iBufLen, - long long* pMaxSize, bool* pCompressed) +void DupeMatcher::FindLargestFile(const char* directory, char* filenameBuf, int bufLen, + long long* maxSize, bool* compressed) { - *pMaxSize = 0; - *pCompressed = false; + *maxSize = 0; + *compressed = false; - DirBrowser dir(szDirectory); + DirBrowser dir(directory); while (const char* filename = dir.Next()) { if (strcmp(filename, ".") && strcmp(filename, "..")) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", szDirectory, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", directory, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - long long lFileSize = Util::FileSize(szFullFilename); - if (lFileSize > *pMaxSize) + long long fileSize = Util::FileSize(fullFilename); + if (fileSize > *maxSize) { - *pMaxSize = lFileSize; - strncpy(szFilenameBuf, filename, iBufLen); - szFilenameBuf[iBufLen-1] = '\0'; + *maxSize = fileSize; + strncpy(filenameBuf, filename, bufLen); + filenameBuf[bufLen-1] = '\0'; } if (Util::MatchFileExt(filename, ".rar", ",")) { - RarLister::FindLargestFile(this, szDirectory, szFilenameBuf, iBufLen, - m_lMaxSize, 60, pMaxSize, pCompressed); + RarLister::FindLargestFile(this, directory, filenameBuf, bufLen, + m_maxSize, 60, maxSize, compressed); return; } } diff --git a/daemon/postprocess/DupeMatcher.h b/daemon/postprocess/DupeMatcher.h index c7051fb0..21972914 100644 --- a/daemon/postprocess/DupeMatcher.h +++ b/daemon/postprocess/DupeMatcher.h @@ -31,25 +31,25 @@ class DupeMatcher { private: - char* m_szDestDir; - long long m_lExpectedSize; - long long m_lMaxSize; - bool m_bCompressed; + char* m_destDir; + long long m_expectedSize; + long long m_maxSize; + bool m_compressed; - void FindLargestFile(const char* szDirectory, char* szFilenameBuf, int iBufLen, - long long* pMaxSize, bool* pCompressed); + void FindLargestFile(const char* directory, char* filenameBuf, int bufLen, + long long* maxSize, bool* compressed); friend class RarLister; protected: - virtual void PrintMessage(Message::EKind eKind, const char* szFormat, ...) {} + virtual void PrintMessage(Message::EKind kind, const char* format, ...) {} public: - DupeMatcher(const char* szDestDir, long long lExpectedSize); + DupeMatcher(const char* destDir, long long expectedSize); ~DupeMatcher(); bool Prepare(); - bool MatchDupeContent(const char* szDupeDir); - static bool SizeDiffOK(long long lSize1, long long lSize2, int iMaxDiffPercent); + bool MatchDupeContent(const char* dupeDir); + static bool SizeDiffOK(long long size1, long long size2, int maxDiffPercent); }; #endif diff --git a/daemon/postprocess/ParChecker.cpp b/daemon/postprocess/ParChecker.cpp index e17b5aa7..dfe47eca 100644 --- a/daemon/postprocess/ParChecker.cpp +++ b/daemon/postprocess/ParChecker.cpp @@ -81,9 +81,9 @@ private: typedef vector Threads; CommandLine commandLine; - ParChecker* m_pOwner; - Threads m_Threads; - bool m_bParallel; + ParChecker* m_owner; + Threads m_threads; + bool m_parallel; Mutex progresslock; virtual void BeginRepair(); @@ -91,17 +91,17 @@ private: void RepairBlock(u32 inputindex, u32 outputindex, size_t blocklength); protected: - virtual void sig_filename(std::string filename) { m_pOwner->signal_filename(filename); } - virtual void sig_progress(int progress) { m_pOwner->signal_progress(progress); } - virtual void sig_done(std::string filename, int available, int total) { m_pOwner->signal_done(filename, available, total); } + virtual void sig_filename(std::string filename) { m_owner->signal_filename(filename); } + virtual void sig_progress(int progress) { m_owner->signal_progress(progress); } + virtual void sig_done(std::string filename, int available, int total) { m_owner->signal_done(filename, available, total); } virtual bool ScanDataFile(DiskFile *diskfile, Par2RepairerSourceFile* &sourcefile, MatchType &matchtype, MD5Hash &hashfull, MD5Hash &hash16k, u32 &count); virtual bool RepairData(u32 inputindex, size_t blocklength); public: - Repairer(ParChecker* pOwner) { m_pOwner = pOwner; } - Result PreProcess(const char *szParFilename); + Repairer(ParChecker* owner) { m_owner = owner; } + Result PreProcess(const char *parFilename); Result Process(bool dorepair); friend class ParChecker; @@ -111,40 +111,40 @@ public: class RepairThread : public Thread { private: - Repairer* m_pOwner; + Repairer* m_owner; u32 m_inputindex; u32 m_outputindex; size_t m_blocklength; - volatile bool m_bWorking; + volatile bool m_working; protected: virtual void Run(); public: - RepairThread(Repairer* pOwner) { this->m_pOwner = pOwner; m_bWorking = false; } + RepairThread(Repairer* owner) { this->m_owner = owner; m_working = false; } void RepairBlock(u32 inputindex, u32 outputindex, size_t blocklength); - bool IsWorking() { return m_bWorking; } + bool IsWorking() { return m_working; } }; -Result Repairer::PreProcess(const char *szParFilename) +Result Repairer::PreProcess(const char *parFilename) { - char szMemParam[20]; - snprintf(szMemParam, 20, "-m%i", g_pOptions->GetParBuffer()); - szMemParam[20-1] = '\0'; + char memParam[20]; + snprintf(memParam, 20, "-m%i", g_pOptions->GetParBuffer()); + memParam[20-1] = '\0'; if (g_pOptions->GetParScan() == Options::psFull) { - char szWildcardParam[1024]; - strncpy(szWildcardParam, szParFilename, 1024); - szWildcardParam[1024-1] = '\0'; - char* szBasename = Util::BaseFileName(szWildcardParam); - if (szBasename != szWildcardParam && strlen(szBasename) > 0) + char wildcardParam[1024]; + strncpy(wildcardParam, parFilename, 1024); + wildcardParam[1024-1] = '\0'; + char* basename = Util::BaseFileName(wildcardParam); + if (basename != wildcardParam && strlen(basename) > 0) { - szBasename[0] = '*'; - szBasename[1] = '\0'; + basename[0] = '*'; + basename[1] = '\0'; } - const char* argv[] = { "par2", "r", "-v", "-v", szMemParam, szParFilename, szWildcardParam }; + const char* argv[] = { "par2", "r", "-v", "-v", memParam, parFilename, wildcardParam }; if (!commandLine.Parse(7, (char**)argv)) { return eInvalidCommandLineArguments; @@ -152,7 +152,7 @@ Result Repairer::PreProcess(const char *szParFilename) } else { - const char* argv[] = { "par2", "r", "-v", "-v", szMemParam, szParFilename }; + const char* argv[] = { "par2", "r", "-v", "-v", memParam, parFilename }; if (!commandLine.Parse(6, (char**)argv)) { return eInvalidCommandLineArguments; @@ -173,7 +173,7 @@ Result Repairer::Process(bool dorepair) bool Repairer::ScanDataFile(DiskFile *diskfile, Par2RepairerSourceFile* &sourcefile, MatchType &matchtype, MD5Hash &hashfull, MD5Hash &hash16k, u32 &count) { - if (m_pOwner->GetParQuick() && sourcefile) + if (m_owner->GetParQuick() && sourcefile) { string path; string name; @@ -181,17 +181,17 @@ bool Repairer::ScanDataFile(DiskFile *diskfile, Par2RepairerSourceFile* &sourcef sig_filename(name); - if (!(m_pOwner->GetStage() == ParChecker::ptVerifyingRepaired && m_pOwner->GetParFull())) + if (!(m_owner->GetStage() == ParChecker::ptVerifyingRepaired && m_owner->GetParFull())) { - int iAvailableBlocks = sourcefile->BlockCount(); - ParChecker::EFileStatus eFileStatus = m_pOwner->VerifyDataFile(diskfile, sourcefile, &iAvailableBlocks); - if (eFileStatus != ParChecker::fsUnknown) + int availableBlocks = sourcefile->BlockCount(); + ParChecker::EFileStatus fileStatus = m_owner->VerifyDataFile(diskfile, sourcefile, &availableBlocks); + if (fileStatus != ParChecker::fsUnknown) { - sig_done(name, iAvailableBlocks, sourcefile->BlockCount()); + sig_done(name, availableBlocks, sourcefile->BlockCount()); sig_progress(1000); - matchtype = eFileStatus == ParChecker::fsSuccess ? eFullMatch : - eFileStatus == ParChecker::fsPartial ? ePartialMatch : eNoMatch; - m_pOwner->SetParFull(false); + matchtype = fileStatus == ParChecker::fsSuccess ? eFullMatch : + fileStatus == ParChecker::fsPartial ? ePartialMatch : eNoMatch; + m_owner->SetParFull(false); return true; } } @@ -202,24 +202,24 @@ bool Repairer::ScanDataFile(DiskFile *diskfile, Par2RepairerSourceFile* &sourcef void Repairer::BeginRepair() { - int iMaxThreads = g_pOptions->GetParThreads() > 0 ? g_pOptions->GetParThreads() : Util::NumberOfCpuCores(); - iMaxThreads = iMaxThreads > 0 ? iMaxThreads : 1; + int maxThreads = g_pOptions->GetParThreads() > 0 ? g_pOptions->GetParThreads() : Util::NumberOfCpuCores(); + maxThreads = maxThreads > 0 ? maxThreads : 1; - int iThreads = iMaxThreads > (int)missingblockcount ? (int)missingblockcount : iMaxThreads; + int threads = maxThreads > (int)missingblockcount ? (int)missingblockcount : maxThreads; - m_pOwner->PrintMessage(Message::mkInfo, "Using %i of max %i thread(s) to repair %i block(s) for %s", - iThreads, iMaxThreads, (int)missingblockcount, m_pOwner->m_szNZBName); + m_owner->PrintMessage(Message::mkInfo, "Using %i of max %i thread(s) to repair %i block(s) for %s", + threads, maxThreads, (int)missingblockcount, m_owner->m_nzbName); - m_bParallel = iThreads > 1; + m_parallel = threads > 1; - if (m_bParallel) + if (m_parallel) { - for (int i = 0; i < iThreads; i++) + for (int i = 0; i < threads; i++) { - RepairThread* pRepairThread = new RepairThread(this); - m_Threads.push_back(pRepairThread); - pRepairThread->SetAutoDestroy(true); - pRepairThread->Start(); + RepairThread* repairThread = new RepairThread(this); + m_threads.push_back(repairThread); + repairThread->SetAutoDestroy(true); + repairThread->Start(); } #ifdef WIN32 @@ -230,12 +230,12 @@ void Repairer::BeginRepair() void Repairer::EndRepair() { - if (m_bParallel) + if (m_parallel) { - for (Threads::iterator it = m_Threads.begin(); it != m_Threads.end(); it++) + for (Threads::iterator it = m_threads.begin(); it != m_threads.end(); it++) { - RepairThread* pRepairThread = (RepairThread*)*it; - pRepairThread->Stop(); + RepairThread* repairThread = (RepairThread*)*it; + repairThread->Stop(); } #ifdef WIN32 @@ -246,22 +246,22 @@ void Repairer::EndRepair() bool Repairer::RepairData(u32 inputindex, size_t blocklength) { - if (!m_bParallel) + if (!m_parallel) { return false; } for (u32 outputindex = 0; outputindex < missingblockcount; ) { - bool bJobAdded = false; - for (Threads::iterator it = m_Threads.begin(); it != m_Threads.end(); it++) + bool jobAdded = false; + for (Threads::iterator it = m_threads.begin(); it != m_threads.end(); it++) { - RepairThread* pRepairThread = (RepairThread*)*it; - if (!pRepairThread->IsWorking()) + RepairThread* repairThread = (RepairThread*)*it; + if (!repairThread->IsWorking()) { - pRepairThread->RepairBlock(inputindex, outputindex, blocklength); + repairThread->RepairBlock(inputindex, outputindex, blocklength); outputindex++; - bJobAdded = true; + jobAdded = true; break; } } @@ -271,23 +271,23 @@ bool Repairer::RepairData(u32 inputindex, size_t blocklength) break; } - if (!bJobAdded) + if (!jobAdded) { usleep(SYNC_SLEEP_INTERVAL); } } // Wait until all m_Threads complete their jobs - bool bWorking = true; - while (bWorking) + bool working = true; + while (working) { - bWorking = false; - for (Threads::iterator it = m_Threads.begin(); it != m_Threads.end(); it++) + working = false; + for (Threads::iterator it = m_threads.begin(); it != m_threads.end(); it++) { - RepairThread* pRepairThread = (RepairThread*)*it; - if (pRepairThread->IsWorking()) + RepairThread* repairThread = (RepairThread*)*it; + if (repairThread->IsWorking()) { - bWorking = true; + working = true; usleep(SYNC_SLEEP_INTERVAL); break; } @@ -325,10 +325,10 @@ void RepairThread::Run() { while (!IsStopped()) { - if (m_bWorking) + if (m_working) { - m_pOwner->RepairBlock(m_inputindex, m_outputindex, m_blocklength); - m_bWorking = false; + m_owner->RepairBlock(m_inputindex, m_outputindex, m_blocklength); + m_working = false; } else { @@ -342,17 +342,17 @@ void RepairThread::RepairBlock(u32 inputindex, u32 outputindex, size_t blockleng m_inputindex = inputindex; m_outputindex = outputindex; m_blocklength = blocklength; - m_bWorking = true; + m_working = true; } class MissingFilesComparator { private: - const char* m_szBaseParFilename; + const char* m_baseParFilename; public: - MissingFilesComparator(const char* szBaseParFilename) : m_szBaseParFilename(szBaseParFilename) {} - bool operator()(CommandLine::ExtraFile* pFirst, CommandLine::ExtraFile* pSecond) const; + MissingFilesComparator(const char* baseParFilename) : m_baseParFilename(baseParFilename) {} + bool operator()(CommandLine::ExtraFile* first, CommandLine::ExtraFile* second) const; }; @@ -360,28 +360,28 @@ public: * Files with the same name as in par-file (and a differnt extension) are * placed at the top of the list to be scanned first. */ -bool MissingFilesComparator::operator()(CommandLine::ExtraFile* pFile1, CommandLine::ExtraFile* pFile2) const +bool MissingFilesComparator::operator()(CommandLine::ExtraFile* file1, CommandLine::ExtraFile* file2) const { char name1[1024]; - strncpy(name1, Util::BaseFileName(pFile1->FileName().c_str()), 1024); + strncpy(name1, Util::BaseFileName(file1->FileName().c_str()), 1024); name1[1024-1] = '\0'; if (char* ext = strrchr(name1, '.')) *ext = '\0'; // trim extension char name2[1024]; - strncpy(name2, Util::BaseFileName(pFile2->FileName().c_str()), 1024); + strncpy(name2, Util::BaseFileName(file2->FileName().c_str()), 1024); name2[1024-1] = '\0'; if (char* ext = strrchr(name2, '.')) *ext = '\0'; // trim extension - return strcmp(name1, m_szBaseParFilename) == 0 && strcmp(name1, name2) != 0; + return strcmp(name1, m_baseParFilename) == 0 && strcmp(name1, name2) != 0; } -ParChecker::Segment::Segment(bool bSuccess, long long iOffset, int iSize, unsigned long lCrc) +ParChecker::Segment::Segment(bool success, long long offset, int size, unsigned long crc) { - m_bSuccess = bSuccess; - m_iOffset = iOffset; - m_iSize = iSize; - m_lCrc = lCrc; + m_success = success; + m_offset = offset; + m_size = size; + m_crc = crc; } @@ -393,16 +393,16 @@ ParChecker::SegmentList::~SegmentList() } } -ParChecker::DupeSource::DupeSource(int iID, const char* szDirectory) +ParChecker::DupeSource::DupeSource(int id, const char* directory) { - m_iID = iID; - m_szDirectory = strdup(szDirectory); - m_iUsedBlocks = 0; + m_id = id; + m_directory = strdup(directory); + m_usedBlocks = 0; } ParChecker::DupeSource::~DupeSource() { - free(m_szDirectory); + free(m_directory); } @@ -410,94 +410,94 @@ ParChecker::ParChecker() { debug("Creating ParChecker"); - m_eStatus = psFailed; - m_szDestDir = NULL; - m_szNZBName = NULL; - m_szParFilename = NULL; - m_szInfoName = NULL; - m_szErrMsg = NULL; - m_szProgressLabel = (char*)malloc(1024); - m_pRepairer = NULL; - m_iFileProgress = 0; - m_iStageProgress = 0; - m_iExtraFiles = 0; - m_iQuickFiles = 0; - m_bVerifyingExtraFiles = false; - m_bCancelled = false; - m_eStage = ptLoadingPars; - m_bParQuick = false; - m_bForceRepair = false; - m_bParFull = false; + m_status = psFailed; + m_destDir = NULL; + m_nzbName = NULL; + m_parFilename = NULL; + m_infoName = NULL; + m_errMsg = NULL; + m_progressLabel = (char*)malloc(1024); + m_repairer = NULL; + m_fileProgress = 0; + m_stageProgress = 0; + m_extraFiles = 0; + m_quickFiles = 0; + m_verifyingExtraFiles = false; + m_cancelled = false; + m_stage = ptLoadingPars; + m_parQuick = false; + m_forceRepair = false; + m_parFull = false; } ParChecker::~ParChecker() { debug("Destroying ParChecker"); - free(m_szDestDir); - free(m_szNZBName); - free(m_szInfoName); - free(m_szProgressLabel); + free(m_destDir); + free(m_nzbName); + free(m_infoName); + free(m_progressLabel); Cleanup(); } void ParChecker::Cleanup() { - delete (Repairer*)m_pRepairer; - m_pRepairer = NULL; + delete (Repairer*)m_repairer; + m_repairer = NULL; - for (FileList::iterator it = m_QueuedParFiles.begin(); it != m_QueuedParFiles.end() ;it++) + for (FileList::iterator it = m_queuedParFiles.begin(); it != m_queuedParFiles.end() ;it++) { free(*it); } - m_QueuedParFiles.clear(); + m_queuedParFiles.clear(); - for (FileList::iterator it = m_ProcessedFiles.begin(); it != m_ProcessedFiles.end() ;it++) + for (FileList::iterator it = m_processedFiles.begin(); it != m_processedFiles.end() ;it++) { free(*it); } - m_ProcessedFiles.clear(); + m_processedFiles.clear(); m_sourceFiles.clear(); - for (DupeSourceList::iterator it = m_DupeSources.begin(); it != m_DupeSources.end() ;it++) + for (DupeSourceList::iterator it = m_dupeSources.begin(); it != m_dupeSources.end() ;it++) { free(*it); } - m_DupeSources.clear(); + m_dupeSources.clear(); - free(m_szErrMsg); - m_szErrMsg = NULL; + free(m_errMsg); + m_errMsg = NULL; } -void ParChecker::SetDestDir(const char * szDestDir) +void ParChecker::SetDestDir(const char * destDir) { - free(m_szDestDir); - m_szDestDir = strdup(szDestDir); + free(m_destDir); + m_destDir = strdup(destDir); } -void ParChecker::SetNZBName(const char * szNZBName) +void ParChecker::SetNZBName(const char * nzbName) { - free(m_szNZBName); - m_szNZBName = strdup(szNZBName); + free(m_nzbName); + m_nzbName = strdup(nzbName); } -void ParChecker::SetInfoName(const char * szInfoName) +void ParChecker::SetInfoName(const char * infoName) { - free(m_szInfoName); - m_szInfoName = strdup(szInfoName); + free(m_infoName); + m_infoName = strdup(infoName); } void ParChecker::Run() { - m_eStatus = RunParCheckAll(); + m_status = RunParCheckAll(); - if (m_eStatus == psRepairNotNeeded && m_bParQuick && m_bForceRepair && !m_bCancelled) + if (m_status == psRepairNotNeeded && m_parQuick && m_forceRepair && !m_cancelled) { - PrintMessage(Message::mkInfo, "Performing full par-check for %s", m_szNZBName); - m_bParQuick = false; - m_eStatus = RunParCheckAll(); + PrintMessage(Message::mkInfo, "Performing full par-check for %s", m_nzbName); + m_parQuick = false; + m_status = RunParCheckAll(); } Completed(); @@ -506,80 +506,80 @@ void ParChecker::Run() ParChecker::EStatus ParChecker::RunParCheckAll() { ParParser::ParFileList fileList; - if (!ParParser::FindMainPars(m_szDestDir, &fileList)) + if (!ParParser::FindMainPars(m_destDir, &fileList)) { - PrintMessage(Message::mkError, "Could not start par-check for %s. Could not find any par-files", m_szNZBName); + PrintMessage(Message::mkError, "Could not start par-check for %s. Could not find any par-files", m_nzbName); return psFailed; } - EStatus eAllStatus = psRepairNotNeeded; - m_bCancelled = false; - m_bParFull = true; + EStatus allStatus = psRepairNotNeeded; + m_cancelled = false; + m_parFull = true; for (ParParser::ParFileList::iterator it = fileList.begin(); it != fileList.end(); it++) { - char* szParFilename = *it; - debug("Found par: %s", szParFilename); + char* parFilename = *it; + debug("Found par: %s", parFilename); - if (!IsStopped() && !m_bCancelled) + if (!IsStopped() && !m_cancelled) { - char szFullParFilename[1024]; - snprintf(szFullParFilename, 1024, "%s%c%s", m_szDestDir, (int)PATH_SEPARATOR, szParFilename); - szFullParFilename[1024-1] = '\0'; + char fullParFilename[1024]; + snprintf(fullParFilename, 1024, "%s%c%s", m_destDir, (int)PATH_SEPARATOR, parFilename); + fullParFilename[1024-1] = '\0'; - char szInfoName[1024]; - int iBaseLen = 0; - ParParser::ParseParFilename(szParFilename, &iBaseLen, NULL); - int maxlen = iBaseLen < 1024 ? iBaseLen : 1024 - 1; - strncpy(szInfoName, szParFilename, maxlen); - szInfoName[maxlen] = '\0'; + char infoName[1024]; + int baseLen = 0; + ParParser::ParseParFilename(parFilename, &baseLen, NULL); + int maxlen = baseLen < 1024 ? baseLen : 1024 - 1; + strncpy(infoName, parFilename, maxlen); + infoName[maxlen] = '\0'; - char szParInfoName[1024]; - snprintf(szParInfoName, 1024, "%s%c%s", m_szNZBName, (int)PATH_SEPARATOR, szInfoName); - szParInfoName[1024-1] = '\0'; + char parInfoName[1024]; + snprintf(parInfoName, 1024, "%s%c%s", m_nzbName, (int)PATH_SEPARATOR, infoName); + parInfoName[1024-1] = '\0'; - SetInfoName(szParInfoName); + SetInfoName(parInfoName); - EStatus eStatus = RunParCheck(szFullParFilename); + EStatus status = RunParCheck(fullParFilename); // accumulate total status, the worst status has priority - if (eAllStatus > eStatus) + if (allStatus > status) { - eAllStatus = eStatus; + allStatus = status; } if (g_pOptions->GetBrokenLog()) { - WriteBrokenLog(eStatus); + WriteBrokenLog(status); } } - free(szParFilename); + free(parFilename); } - return eAllStatus; + return allStatus; } -ParChecker::EStatus ParChecker::RunParCheck(const char* szParFilename) +ParChecker::EStatus ParChecker::RunParCheck(const char* parFilename) { Cleanup(); - m_szParFilename = szParFilename; - m_eStage = ptLoadingPars; - m_iProcessedFiles = 0; - m_iExtraFiles = 0; - m_iQuickFiles = 0; - m_bVerifyingExtraFiles = false; - m_bHasDamagedFiles = false; - EStatus eStatus = psFailed; + m_parFilename = parFilename; + m_stage = ptLoadingPars; + m_processedCount = 0; + m_extraFiles = 0; + m_quickFiles = 0; + m_verifyingExtraFiles = false; + m_hasDamagedFiles = false; + EStatus status = psFailed; - PrintMessage(Message::mkInfo, "Verifying %s", m_szInfoName); + PrintMessage(Message::mkInfo, "Verifying %s", m_infoName); - debug("par: %s", m_szParFilename); + debug("par: %s", m_parFilename); - snprintf(m_szProgressLabel, 1024, "Verifying %s", m_szInfoName); - m_szProgressLabel[1024-1] = '\0'; - m_iFileProgress = 0; - m_iStageProgress = 0; + snprintf(m_progressLabel, 1024, "Verifying %s", m_infoName); + m_progressLabel[1024-1] = '\0'; + m_fileProgress = 0; + m_stageProgress = 0; UpdateProgress(); Result res = (Result)PreProcessPar(); @@ -589,47 +589,47 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* szParFilename) return psFailed; } - m_eStage = ptVerifyingSources; - Repairer* pRepairer = (Repairer*)m_pRepairer; - res = pRepairer->Process(false); + m_stage = ptVerifyingSources; + Repairer* repairer = (Repairer*)m_repairer; + res = repairer->Process(false); - if (!m_bParQuick) + if (!m_parQuick) { CheckEmptyFiles(); } - bool bAddedSplittedFragments = false; - if (m_bHasDamagedFiles && !IsStopped() && res == eRepairNotPossible) + bool addedSplittedFragments = false; + if (m_hasDamagedFiles && !IsStopped() && res == eRepairNotPossible) { - bAddedSplittedFragments = AddSplittedFragments(); - if (bAddedSplittedFragments) + addedSplittedFragments = AddSplittedFragments(); + if (addedSplittedFragments) { - res = pRepairer->Process(false); + res = repairer->Process(false); } } - if (m_bHasDamagedFiles && !IsStopped() && pRepairer->missingfilecount > 0 && - !(bAddedSplittedFragments && res == eRepairPossible) && + if (m_hasDamagedFiles && !IsStopped() && repairer->missingfilecount > 0 && + !(addedSplittedFragments && res == eRepairPossible) && (g_pOptions->GetParScan() == Options::psExtended || g_pOptions->GetParScan() == Options::psDupe)) { if (AddMissingFiles()) { - res = pRepairer->Process(false); + res = repairer->Process(false); } } - if (m_bHasDamagedFiles && !IsStopped() && res == eRepairNotPossible) + if (m_hasDamagedFiles && !IsStopped() && res == eRepairNotPossible) { res = (Result)ProcessMorePars(); } - if (m_bHasDamagedFiles && !IsStopped() && res == eRepairNotPossible && + if (m_hasDamagedFiles && !IsStopped() && res == eRepairNotPossible && g_pOptions->GetParScan() == Options::psDupe) { if (AddDupeFiles()) { - res = pRepairer->Process(false); + res = repairer->Process(false); if (!IsStopped() && res == eRepairNotPossible) { res = (Result)ProcessMorePars(); @@ -643,71 +643,71 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* szParFilename) return psFailed; } - eStatus = psFailed; + status = psFailed; - if (res == eSuccess || !m_bHasDamagedFiles) + if (res == eSuccess || !m_hasDamagedFiles) { - PrintMessage(Message::mkInfo, "Repair not needed for %s", m_szInfoName); - eStatus = psRepairNotNeeded; + PrintMessage(Message::mkInfo, "Repair not needed for %s", m_infoName); + status = psRepairNotNeeded; } else if (res == eRepairPossible) { - eStatus = psRepairPossible; + status = psRepairPossible; if (g_pOptions->GetParRepair()) { - PrintMessage(Message::mkInfo, "Repairing %s", m_szInfoName); + PrintMessage(Message::mkInfo, "Repairing %s", m_infoName); SaveSourceList(); - snprintf(m_szProgressLabel, 1024, "Repairing %s", m_szInfoName); - m_szProgressLabel[1024-1] = '\0'; - m_iFileProgress = 0; - m_iStageProgress = 0; - m_iProcessedFiles = 0; - m_eStage = ptRepairing; - m_iFilesToRepair = pRepairer->damagedfilecount + pRepairer->missingfilecount; + snprintf(m_progressLabel, 1024, "Repairing %s", m_infoName); + m_progressLabel[1024-1] = '\0'; + m_fileProgress = 0; + m_stageProgress = 0; + m_processedCount = 0; + m_stage = ptRepairing; + m_filesToRepair = repairer->damagedfilecount + repairer->missingfilecount; UpdateProgress(); - res = pRepairer->Process(true); + res = repairer->Process(true); if (res == eSuccess) { - PrintMessage(Message::mkInfo, "Successfully repaired %s", m_szInfoName); - eStatus = psRepaired; - StatDupeSources(&m_DupeSources); + PrintMessage(Message::mkInfo, "Successfully repaired %s", m_infoName); + status = psRepaired; + StatDupeSources(&m_dupeSources); DeleteLeftovers(); } } else { - PrintMessage(Message::mkInfo, "Repair possible for %s", m_szInfoName); + PrintMessage(Message::mkInfo, "Repair possible for %s", m_infoName); } } - if (m_bCancelled) + if (m_cancelled) { - if (m_eStage >= ptRepairing) + if (m_stage >= ptRepairing) { - PrintMessage(Message::mkWarning, "Repair cancelled for %s", m_szInfoName); - m_szErrMsg = strdup("repair cancelled"); - eStatus = psRepairPossible; + PrintMessage(Message::mkWarning, "Repair cancelled for %s", m_infoName); + m_errMsg = strdup("repair cancelled"); + status = psRepairPossible; } else { - PrintMessage(Message::mkWarning, "Par-check cancelled for %s", m_szInfoName); - m_szErrMsg = strdup("par-check cancelled"); - eStatus = psFailed; + PrintMessage(Message::mkWarning, "Par-check cancelled for %s", m_infoName); + m_errMsg = strdup("par-check cancelled"); + status = psFailed; } } - else if (eStatus == psFailed) + else if (status == psFailed) { - if (!m_szErrMsg && (int)res >= 0 && (int)res <= 8) + if (!m_errMsg && (int)res >= 0 && (int)res <= 8) { - m_szErrMsg = strdup(Par2CmdLineErrStr[res]); + m_errMsg = strdup(Par2CmdLineErrStr[res]); } - PrintMessage(Message::mkError, "Repair failed for %s: %s", m_szInfoName, m_szErrMsg ? m_szErrMsg : ""); + PrintMessage(Message::mkError, "Repair failed for %s: %s", m_infoName, m_errMsg ? m_errMsg : ""); } Cleanup(); - return eStatus; + return status; } int ParChecker::PreProcessPar() @@ -717,32 +717,32 @@ int ParChecker::PreProcessPar() { Cleanup(); - Repairer* pRepairer = new Repairer(this); - m_pRepairer = pRepairer; + Repairer* repairer = new Repairer(this); + m_repairer = repairer; - res = pRepairer->PreProcess(m_szParFilename); + res = repairer->PreProcess(m_parFilename); debug("ParChecker: PreProcess-result=%i", res); if (IsStopped()) { - PrintMessage(Message::mkError, "Could not verify %s: stopping", m_szInfoName); - m_szErrMsg = strdup("par-check was stopped"); + PrintMessage(Message::mkError, "Could not verify %s: stopping", m_infoName); + m_errMsg = strdup("par-check was stopped"); return eRepairFailed; } if (res == eInvalidCommandLineArguments) { - PrintMessage(Message::mkError, "Could not start par-check for %s. Par-file: %s", m_szInfoName, m_szParFilename); - m_szErrMsg = strdup("Command line could not be parsed"); + PrintMessage(Message::mkError, "Could not start par-check for %s. Par-file: %s", m_infoName, m_parFilename); + m_errMsg = strdup("Command line could not be parsed"); return res; } if (res != eSuccess) { - PrintMessage(Message::mkWarning, "Could not verify %s: par2-file could not be processed", m_szInfoName); - PrintMessage(Message::mkInfo, "Requesting more par2-files for %s", m_szInfoName); - bool bHasMorePars = LoadMainParBak(); - if (!bHasMorePars) + PrintMessage(Message::mkWarning, "Could not verify %s: par2-file could not be processed", m_infoName); + PrintMessage(Message::mkInfo, "Requesting more par2-files for %s", m_infoName); + bool hasMorePars = LoadMainParBak(); + if (!hasMorePars) { PrintMessage(Message::mkWarning, "No more par2-files found"); break; @@ -752,8 +752,8 @@ int ParChecker::PreProcessPar() if (res != eSuccess) { - PrintMessage(Message::mkError, "Could not verify %s: par2-file could not be processed", m_szInfoName); - m_szErrMsg = strdup("par2-file could not be processed"); + PrintMessage(Message::mkError, "Could not verify %s: par2-file could not be processed", m_infoName); + m_errMsg = strdup("par2-file could not be processed"); return res; } @@ -764,34 +764,34 @@ bool ParChecker::LoadMainParBak() { while (!IsStopped()) { - m_mutexQueuedParFiles.Lock(); - bool hasMorePars = !m_QueuedParFiles.empty(); - for (FileList::iterator it = m_QueuedParFiles.begin(); it != m_QueuedParFiles.end() ;it++) + m_queuedParFilesMutex.Lock(); + bool hasMorePars = !m_queuedParFiles.empty(); + for (FileList::iterator it = m_queuedParFiles.begin(); it != m_queuedParFiles.end() ;it++) { free(*it); } - m_QueuedParFiles.clear(); - m_mutexQueuedParFiles.Unlock(); + m_queuedParFiles.clear(); + m_queuedParFilesMutex.Unlock(); if (hasMorePars) { return true; } - int iBlockFound = 0; - bool requested = RequestMorePars(1, &iBlockFound); + int blockFound = 0; + bool requested = RequestMorePars(1, &blockFound); if (requested) { - strncpy(m_szProgressLabel, "Awaiting additional par-files", 1024); - m_szProgressLabel[1024-1] = '\0'; - m_iFileProgress = 0; + strncpy(m_progressLabel, "Awaiting additional par-files", 1024); + m_progressLabel[1024-1] = '\0'; + m_fileProgress = 0; UpdateProgress(); } - m_mutexQueuedParFiles.Lock(); - hasMorePars = !m_QueuedParFiles.empty(); - m_bQueuedParFilesChanged = false; - m_mutexQueuedParFiles.Unlock(); + m_queuedParFilesMutex.Lock(); + hasMorePars = !m_queuedParFiles.empty(); + m_queuedParFilesChanged = false; + m_queuedParFilesMutex.Unlock(); if (!requested && !hasMorePars) { @@ -801,12 +801,12 @@ bool ParChecker::LoadMainParBak() if (!hasMorePars) { // wait until new files are added by "AddParFile" or a change is signaled by "QueueChanged" - bool bQueuedParFilesChanged = false; - while (!bQueuedParFilesChanged && !IsStopped() && !m_bCancelled) + bool queuedParFilesChanged = false; + while (!queuedParFilesChanged && !IsStopped() && !m_cancelled) { - m_mutexQueuedParFiles.Lock(); - bQueuedParFilesChanged = m_bQueuedParFilesChanged; - m_mutexQueuedParFiles.Unlock(); + m_queuedParFilesMutex.Lock(); + queuedParFilesChanged = m_queuedParFilesChanged; + m_queuedParFilesMutex.Unlock(); usleep(100 * 1000); } } @@ -818,75 +818,75 @@ bool ParChecker::LoadMainParBak() int ParChecker::ProcessMorePars() { Result res = eRepairNotPossible; - Repairer* pRepairer = (Repairer*)m_pRepairer; + Repairer* repairer = (Repairer*)m_repairer; - bool bMoreFilesLoaded = true; + bool moreFilesLoaded = true; while (!IsStopped() && res == eRepairNotPossible) { - int missingblockcount = pRepairer->missingblockcount - pRepairer->recoverypacketmap.size(); + int missingblockcount = repairer->missingblockcount - repairer->recoverypacketmap.size(); if (missingblockcount <= 0) { return eRepairPossible; } - if (bMoreFilesLoaded) + if (moreFilesLoaded) { - PrintMessage(Message::mkInfo, "Need more %i par-block(s) for %s", missingblockcount, m_szInfoName); + PrintMessage(Message::mkInfo, "Need more %i par-block(s) for %s", missingblockcount, m_infoName); } - m_mutexQueuedParFiles.Lock(); - bool hasMorePars = !m_QueuedParFiles.empty(); - m_mutexQueuedParFiles.Unlock(); + m_queuedParFilesMutex.Lock(); + bool hasMorePars = !m_queuedParFiles.empty(); + m_queuedParFilesMutex.Unlock(); if (!hasMorePars) { - int iBlockFound = 0; - bool requested = RequestMorePars(missingblockcount, &iBlockFound); + int blockFound = 0; + bool requested = RequestMorePars(missingblockcount, &blockFound); if (requested) { - strncpy(m_szProgressLabel, "Awaiting additional par-files", 1024); - m_szProgressLabel[1024-1] = '\0'; - m_iFileProgress = 0; + strncpy(m_progressLabel, "Awaiting additional par-files", 1024); + m_progressLabel[1024-1] = '\0'; + m_fileProgress = 0; UpdateProgress(); } - m_mutexQueuedParFiles.Lock(); - hasMorePars = !m_QueuedParFiles.empty(); - m_bQueuedParFilesChanged = false; - m_mutexQueuedParFiles.Unlock(); + m_queuedParFilesMutex.Lock(); + hasMorePars = !m_queuedParFiles.empty(); + m_queuedParFilesChanged = false; + m_queuedParFilesMutex.Unlock(); if (!requested && !hasMorePars) { - m_szErrMsg = (char*)malloc(1024); - snprintf(m_szErrMsg, 1024, "not enough par-blocks, %i block(s) needed, but %i block(s) available", missingblockcount, iBlockFound); - m_szErrMsg[1024-1] = '\0'; + m_errMsg = (char*)malloc(1024); + snprintf(m_errMsg, 1024, "not enough par-blocks, %i block(s) needed, but %i block(s) available", missingblockcount, blockFound); + m_errMsg[1024-1] = '\0'; break; } if (!hasMorePars) { // wait until new files are added by "AddParFile" or a change is signaled by "QueueChanged" - bool bQueuedParFilesChanged = false; - while (!bQueuedParFilesChanged && !IsStopped() && !m_bCancelled) + bool queuedParFilesChanged = false; + while (!queuedParFilesChanged && !IsStopped() && !m_cancelled) { - m_mutexQueuedParFiles.Lock(); - bQueuedParFilesChanged = m_bQueuedParFilesChanged; - m_mutexQueuedParFiles.Unlock(); + m_queuedParFilesMutex.Lock(); + queuedParFilesChanged = m_queuedParFilesChanged; + m_queuedParFilesMutex.Unlock(); usleep(100 * 1000); } } } - if (IsStopped() || m_bCancelled) + if (IsStopped() || m_cancelled) { break; } - bMoreFilesLoaded = LoadMorePars(); - if (bMoreFilesLoaded) + moreFilesLoaded = LoadMorePars(); + if (moreFilesLoaded) { - pRepairer->UpdateVerificationResults(); - res = pRepairer->Process(false); + repairer->UpdateVerificationResults(); + res = repairer->Process(false); } } @@ -895,68 +895,68 @@ int ParChecker::ProcessMorePars() bool ParChecker::LoadMorePars() { - m_mutexQueuedParFiles.Lock(); + m_queuedParFilesMutex.Lock(); FileList moreFiles; - moreFiles.assign(m_QueuedParFiles.begin(), m_QueuedParFiles.end()); - m_QueuedParFiles.clear(); - m_mutexQueuedParFiles.Unlock(); + moreFiles.assign(m_queuedParFiles.begin(), m_queuedParFiles.end()); + m_queuedParFiles.clear(); + m_queuedParFilesMutex.Unlock(); for (FileList::iterator it = moreFiles.begin(); it != moreFiles.end() ;it++) { - char* szParFilename = *it; - bool loadedOK = ((Repairer*)m_pRepairer)->LoadPacketsFromFile(szParFilename); + char* parFilename = *it; + bool loadedOK = ((Repairer*)m_repairer)->LoadPacketsFromFile(parFilename); if (loadedOK) { - PrintMessage(Message::mkInfo, "File %s successfully loaded for par-check", Util::BaseFileName(szParFilename), m_szInfoName); + PrintMessage(Message::mkInfo, "File %s successfully loaded for par-check", Util::BaseFileName(parFilename), m_infoName); } else { - PrintMessage(Message::mkInfo, "Could not load file %s for par-check", Util::BaseFileName(szParFilename), m_szInfoName); + PrintMessage(Message::mkInfo, "Could not load file %s for par-check", Util::BaseFileName(parFilename), m_infoName); } - free(szParFilename); + free(parFilename); } return !moreFiles.empty(); } -void ParChecker::AddParFile(const char * szParFilename) +void ParChecker::AddParFile(const char * parFilename) { - m_mutexQueuedParFiles.Lock(); - m_QueuedParFiles.push_back(strdup(szParFilename)); - m_bQueuedParFilesChanged = true; - m_mutexQueuedParFiles.Unlock(); + m_queuedParFilesMutex.Lock(); + m_queuedParFiles.push_back(strdup(parFilename)); + m_queuedParFilesChanged = true; + m_queuedParFilesMutex.Unlock(); } void ParChecker::QueueChanged() { - m_mutexQueuedParFiles.Lock(); - m_bQueuedParFilesChanged = true; - m_mutexQueuedParFiles.Unlock(); + m_queuedParFilesMutex.Lock(); + m_queuedParFilesChanged = true; + m_queuedParFilesMutex.Unlock(); } bool ParChecker::AddSplittedFragments() { std::list extrafiles; - DirBrowser dir(m_szDestDir); + DirBrowser dir(m_destDir); while (const char* filename = dir.Next()) { if (strcmp(filename, ".") && strcmp(filename, "..") && strcmp(filename, "_brokenlog.txt") && !IsParredFile(filename) && !IsProcessedFile(filename)) { - for (std::vector::iterator it = ((Repairer*)m_pRepairer)->sourcefiles.begin(); - it != ((Repairer*)m_pRepairer)->sourcefiles.end(); it++) + for (std::vector::iterator it = ((Repairer*)m_repairer)->sourcefiles.begin(); + it != ((Repairer*)m_repairer)->sourcefiles.end(); it++) { Par2RepairerSourceFile *sourcefile = *it; std::string target = sourcefile->TargetFileName(); - const char* szFilename2 = target.c_str(); - const char* szBasename2 = Util::BaseFileName(szFilename2); - int iBaseLen = strlen(szBasename2); + const char* filename2 = target.c_str(); + const char* basename2 = Util::BaseFileName(filename2); + int baseLen = strlen(basename2); - if (!strncasecmp(filename, szBasename2, iBaseLen)) + if (!strncasecmp(filename, basename2, baseLen)) { - const char* p = filename + iBaseLen; + const char* p = filename + baseLen; if (*p == '.') { for (p++; *p && strchr("0123456789", *p); p++) ; @@ -965,7 +965,7 @@ bool ParChecker::AddSplittedFragments() debug("Found splitted fragment %s", filename); char fullfilename[1024]; - snprintf(fullfilename, 1024, "%s%c%s", m_szDestDir, PATH_SEPARATOR, filename); + snprintf(fullfilename, 1024, "%s%c%s", m_destDir, PATH_SEPARATOR, filename); fullfilename[1024-1] = '\0'; CommandLine::ExtraFile extrafile(fullfilename, Util::FileSize(fullfilename)); @@ -977,60 +977,60 @@ bool ParChecker::AddSplittedFragments() } } - bool bFragmentsAdded = false; + bool fragmentsAdded = false; if (!extrafiles.empty()) { - m_iExtraFiles += extrafiles.size(); - m_bVerifyingExtraFiles = true; - PrintMessage(Message::mkInfo, "Found %i splitted fragments for %s", (int)extrafiles.size(), m_szInfoName); - bFragmentsAdded = ((Repairer*)m_pRepairer)->VerifyExtraFiles(extrafiles); - ((Repairer*)m_pRepairer)->UpdateVerificationResults(); - m_bVerifyingExtraFiles = false; + m_extraFiles += extrafiles.size(); + m_verifyingExtraFiles = true; + PrintMessage(Message::mkInfo, "Found %i splitted fragments for %s", (int)extrafiles.size(), m_infoName); + fragmentsAdded = ((Repairer*)m_repairer)->VerifyExtraFiles(extrafiles); + ((Repairer*)m_repairer)->UpdateVerificationResults(); + m_verifyingExtraFiles = false; } - return bFragmentsAdded; + return fragmentsAdded; } bool ParChecker::AddMissingFiles() { - return AddExtraFiles(true, false, m_szDestDir); + return AddExtraFiles(true, false, m_destDir); } bool ParChecker::AddDupeFiles() { - char szDirectory[1024]; - strncpy(szDirectory, m_szParFilename, 1024); - szDirectory[1024-1] = '\0'; + char directory[1024]; + strncpy(directory, m_parFilename, 1024); + directory[1024-1] = '\0'; - bool bAdded = AddExtraFiles(false, false, szDirectory); + bool added = AddExtraFiles(false, false, directory); - if (((Repairer*)m_pRepairer)->missingblockcount > 0) + if (((Repairer*)m_repairer)->missingblockcount > 0) { // scanning directories of duplicates - RequestDupeSources(&m_DupeSources); + RequestDupeSources(&m_dupeSources); - if (!m_DupeSources.empty()) + if (!m_dupeSources.empty()) { - int iWasBlocksMissing = ((Repairer*)m_pRepairer)->missingblockcount; + int wasBlocksMissing = ((Repairer*)m_repairer)->missingblockcount; - for (DupeSourceList::iterator it = m_DupeSources.begin(); it != m_DupeSources.end(); it++) + for (DupeSourceList::iterator it = m_dupeSources.begin(); it != m_dupeSources.end(); it++) { - DupeSource* pDupeSource = *it; - if (((Repairer*)m_pRepairer)->missingblockcount > 0 && Util::DirectoryExists(pDupeSource->GetDirectory())) + DupeSource* dupeSource = *it; + if (((Repairer*)m_repairer)->missingblockcount > 0 && Util::DirectoryExists(dupeSource->GetDirectory())) { - int iWasBlocksMissing2 = ((Repairer*)m_pRepairer)->missingblockcount; - bool bOneAdded = AddExtraFiles(false, true, pDupeSource->GetDirectory()); - bAdded |= bOneAdded; - int iBlocksMissing2 = ((Repairer*)m_pRepairer)->missingblockcount; - pDupeSource->SetUsedBlocks(pDupeSource->GetUsedBlocks() + (iWasBlocksMissing2 - iBlocksMissing2)); + int wasBlocksMissing2 = ((Repairer*)m_repairer)->missingblockcount; + bool oneAdded = AddExtraFiles(false, true, dupeSource->GetDirectory()); + added |= oneAdded; + int blocksMissing2 = ((Repairer*)m_repairer)->missingblockcount; + dupeSource->SetUsedBlocks(dupeSource->GetUsedBlocks() + (wasBlocksMissing2 - blocksMissing2)); } } - int iBlocksMissing = ((Repairer*)m_pRepairer)->missingblockcount; - if (iBlocksMissing < iWasBlocksMissing) + int blocksMissing = ((Repairer*)m_repairer)->missingblockcount; + if (blocksMissing < wasBlocksMissing) { - PrintMessage(Message::mkInfo, "Found extra %i blocks in dupe sources", iWasBlocksMissing - iBlocksMissing); + PrintMessage(Message::mkInfo, "Found extra %i blocks in dupe sources", wasBlocksMissing - blocksMissing); } else { @@ -1039,30 +1039,30 @@ bool ParChecker::AddDupeFiles() } } - return bAdded; + return added; } -bool ParChecker::AddExtraFiles(bool bOnlyMissing, bool bExternalDir, const char* szDirectory) +bool ParChecker::AddExtraFiles(bool onlyMissing, bool externalDir, const char* directory) { - if (bExternalDir) + if (externalDir) { - PrintMessage(Message::mkInfo, "Performing dupe par-scan for %s in %s", m_szInfoName, Util::BaseFileName(szDirectory)); + PrintMessage(Message::mkInfo, "Performing dupe par-scan for %s in %s", m_infoName, Util::BaseFileName(directory)); } else { - PrintMessage(Message::mkInfo, "Performing extra par-scan for %s", m_szInfoName); + PrintMessage(Message::mkInfo, "Performing extra par-scan for %s", m_infoName); } std::list extrafiles; - DirBrowser dir(szDirectory); + DirBrowser dir(directory); while (const char* filename = dir.Next()) { if (strcmp(filename, ".") && strcmp(filename, "..") && strcmp(filename, "_brokenlog.txt") && - (bExternalDir || (!IsParredFile(filename) && !IsProcessedFile(filename)))) + (externalDir || (!IsParredFile(filename) && !IsProcessedFile(filename)))) { char fullfilename[1024]; - snprintf(fullfilename, 1024, "%s%c%s", szDirectory, PATH_SEPARATOR, filename); + snprintf(fullfilename, 1024, "%s%c%s", directory, PATH_SEPARATOR, filename); fullfilename[1024-1] = '\0'; extrafiles.push_back(new CommandLine::ExtraFile(fullfilename, Util::FileSize(fullfilename))); @@ -1070,67 +1070,67 @@ bool ParChecker::AddExtraFiles(bool bOnlyMissing, bool bExternalDir, const char* } // Sort the list - char* szBaseParFilename = strdup(Util::BaseFileName(m_szParFilename)); - if (char* ext = strrchr(szBaseParFilename, '.')) *ext = '\0'; // trim extension - extrafiles.sort(MissingFilesComparator(szBaseParFilename)); - free(szBaseParFilename); + char* baseParFilename = strdup(Util::BaseFileName(m_parFilename)); + if (char* ext = strrchr(baseParFilename, '.')) *ext = '\0'; // trim extension + extrafiles.sort(MissingFilesComparator(baseParFilename)); + free(baseParFilename); // Scan files - bool bFilesAdded = false; + bool filesAdded = false; if (!extrafiles.empty()) { - m_iExtraFiles += extrafiles.size(); - m_bVerifyingExtraFiles = true; + m_extraFiles += extrafiles.size(); + m_verifyingExtraFiles = true; std::list extrafiles1; // adding files one by one until all missing files are found - while (!IsStopped() && !m_bCancelled && extrafiles.size() > 0) + while (!IsStopped() && !m_cancelled && extrafiles.size() > 0) { - CommandLine::ExtraFile* pExtraFile = extrafiles.front(); + CommandLine::ExtraFile* extraFile = extrafiles.front(); extrafiles.pop_front(); extrafiles1.clear(); - extrafiles1.push_back(*pExtraFile); + extrafiles1.push_back(*extraFile); - int iWasFilesMissing = ((Repairer*)m_pRepairer)->missingfilecount; - int iWasBlocksMissing = ((Repairer*)m_pRepairer)->missingblockcount; + int wasFilesMissing = ((Repairer*)m_repairer)->missingfilecount; + int wasBlocksMissing = ((Repairer*)m_repairer)->missingblockcount; - ((Repairer*)m_pRepairer)->VerifyExtraFiles(extrafiles1); - ((Repairer*)m_pRepairer)->UpdateVerificationResults(); + ((Repairer*)m_repairer)->VerifyExtraFiles(extrafiles1); + ((Repairer*)m_repairer)->UpdateVerificationResults(); - bool bFileAdded = iWasFilesMissing > (int)((Repairer*)m_pRepairer)->missingfilecount; - bool bBlockAdded = iWasBlocksMissing > (int)((Repairer*)m_pRepairer)->missingblockcount; + bool fileAdded = wasFilesMissing > (int)((Repairer*)m_repairer)->missingfilecount; + bool blockAdded = wasBlocksMissing > (int)((Repairer*)m_repairer)->missingblockcount; - if (bFileAdded && !bExternalDir) + if (fileAdded && !externalDir) { - PrintMessage(Message::mkInfo, "Found missing file %s", Util::BaseFileName(pExtraFile->FileName().c_str())); - RegisterParredFile(Util::BaseFileName(pExtraFile->FileName().c_str())); + PrintMessage(Message::mkInfo, "Found missing file %s", Util::BaseFileName(extraFile->FileName().c_str())); + RegisterParredFile(Util::BaseFileName(extraFile->FileName().c_str())); } - else if (bBlockAdded) + else if (blockAdded) { - PrintMessage(Message::mkInfo, "Found %i missing blocks", iWasBlocksMissing - (int)((Repairer*)m_pRepairer)->missingblockcount); + PrintMessage(Message::mkInfo, "Found %i missing blocks", wasBlocksMissing - (int)((Repairer*)m_repairer)->missingblockcount); } - bFilesAdded |= bFileAdded | bBlockAdded; + filesAdded |= fileAdded | blockAdded; - delete pExtraFile; + delete extraFile; - if (bOnlyMissing && ((Repairer*)m_pRepairer)->missingfilecount == 0) + if (onlyMissing && ((Repairer*)m_repairer)->missingfilecount == 0) { PrintMessage(Message::mkInfo, "All missing files found, aborting par-scan"); break; } - if (!bOnlyMissing && ((Repairer*)m_pRepairer)->missingblockcount == 0) + if (!onlyMissing && ((Repairer*)m_repairer)->missingblockcount == 0) { PrintMessage(Message::mkInfo, "All missing blocks found, aborting par-scan"); break; } } - m_bVerifyingExtraFiles = false; + m_verifyingExtraFiles = false; // free any remaining objects for (std::list::iterator it = extrafiles.begin(); it != extrafiles.end() ;it++) @@ -1139,15 +1139,15 @@ bool ParChecker::AddExtraFiles(bool bOnlyMissing, bool bExternalDir, const char* } } - return bFilesAdded; + return filesAdded; } -bool ParChecker::IsProcessedFile(const char* szFilename) +bool ParChecker::IsProcessedFile(const char* filename) { - for (FileList::iterator it = m_ProcessedFiles.begin(); it != m_ProcessedFiles.end(); it++) + for (FileList::iterator it = m_processedFiles.begin(); it != m_processedFiles.end(); it++) { - const char* szProcessedFilename = *it; - if (!strcasecmp(Util::BaseFileName(szProcessedFilename), szFilename)) + const char* processedFilename = *it; + if (!strcasecmp(Util::BaseFileName(processedFilename), filename)) { return true; } @@ -1165,128 +1165,128 @@ void ParChecker::signal_filename(std::string str) m_lastFilename = str; - const char* szStageMessage[] = { "Loading file", "Verifying file", "Repairing file", "Verifying repaired file" }; + const char* stageMessage[] = { "Loading file", "Verifying file", "Repairing file", "Verifying repaired file" }; - if (m_eStage == ptRepairing) + if (m_stage == ptRepairing) { - m_eStage = ptVerifyingRepaired; + m_stage = ptVerifyingRepaired; } // don't print progress messages when verifying repaired files in quick verification mode, // because repaired files are not verified in this mode - if (!(m_eStage == ptVerifyingRepaired && m_bParQuick)) + if (!(m_stage == ptVerifyingRepaired && m_parQuick)) { - PrintMessage(Message::mkInfo, "%s %s", szStageMessage[m_eStage], str.c_str()); + PrintMessage(Message::mkInfo, "%s %s", stageMessage[m_stage], str.c_str()); } - if (m_eStage == ptLoadingPars || m_eStage == ptVerifyingSources) + if (m_stage == ptLoadingPars || m_stage == ptVerifyingSources) { - m_ProcessedFiles.push_back(strdup(str.c_str())); + m_processedFiles.push_back(strdup(str.c_str())); } - snprintf(m_szProgressLabel, 1024, "%s %s", szStageMessage[m_eStage], str.c_str()); - m_szProgressLabel[1024-1] = '\0'; - m_iFileProgress = 0; + snprintf(m_progressLabel, 1024, "%s %s", stageMessage[m_stage], str.c_str()); + m_progressLabel[1024-1] = '\0'; + m_fileProgress = 0; UpdateProgress(); } void ParChecker::signal_progress(int progress) { - m_iFileProgress = (int)progress; + m_fileProgress = (int)progress; - if (m_eStage == ptRepairing) + if (m_stage == ptRepairing) { // calculating repair-data for all files - m_iStageProgress = m_iFileProgress; + m_stageProgress = m_fileProgress; } else { // processing individual files - int iTotalFiles = 0; - int iProcessedFiles = m_iProcessedFiles; - if (m_eStage == ptVerifyingRepaired) + int totalFiles = 0; + int processedFiles = m_processedCount; + if (m_stage == ptVerifyingRepaired) { // repairing individual files - iTotalFiles = m_iFilesToRepair; + totalFiles = m_filesToRepair; } else { // verifying individual files - iTotalFiles = ((Repairer*)m_pRepairer)->sourcefiles.size() + m_iExtraFiles; - if (m_iExtraFiles > 0) + totalFiles = ((Repairer*)m_repairer)->sourcefiles.size() + m_extraFiles; + if (m_extraFiles > 0) { // during extra par scan don't count quickly verified files; // extra files require much more time for verification; // counting only fully scanned files improves estimated time accuracy. - iTotalFiles -= m_iQuickFiles; - iProcessedFiles -= m_iQuickFiles; + totalFiles -= m_quickFiles; + processedFiles -= m_quickFiles; } } - if (iTotalFiles > 0) + if (totalFiles > 0) { - if (m_iFileProgress < 1000) + if (m_fileProgress < 1000) { - m_iStageProgress = (iProcessedFiles * 1000 + m_iFileProgress) / iTotalFiles; + m_stageProgress = (processedFiles * 1000 + m_fileProgress) / totalFiles; } else { - m_iStageProgress = iProcessedFiles * 1000 / iTotalFiles; + m_stageProgress = processedFiles * 1000 / totalFiles; } } else { - m_iStageProgress = 0; + m_stageProgress = 0; } } - debug("Current-progress: %i, Total-progress: %i", m_iFileProgress, m_iStageProgress); + debug("Current-progress: %i, Total-progress: %i", m_fileProgress, m_stageProgress); UpdateProgress(); } void ParChecker::signal_done(std::string str, int available, int total) { - m_iProcessedFiles++; + m_processedCount++; - if (m_eStage == ptVerifyingSources) + if (m_stage == ptVerifyingSources) { - if (available < total && !m_bVerifyingExtraFiles) + if (available < total && !m_verifyingExtraFiles) { - const char* szFilename = str.c_str(); + const char* filename = str.c_str(); - bool bFileExists = true; - for (std::vector::iterator it = ((Repairer*)m_pRepairer)->sourcefiles.begin(); - it != ((Repairer*)m_pRepairer)->sourcefiles.end(); it++) + bool fileExists = true; + for (std::vector::iterator it = ((Repairer*)m_repairer)->sourcefiles.begin(); + it != ((Repairer*)m_repairer)->sourcefiles.end(); it++) { Par2RepairerSourceFile *sourcefile = *it; - if (sourcefile && !strcmp(szFilename, Util::BaseFileName(sourcefile->TargetFileName().c_str())) && + if (sourcefile && !strcmp(filename, Util::BaseFileName(sourcefile->TargetFileName().c_str())) && !sourcefile->GetTargetExists()) { - bFileExists = false; + fileExists = false; break; } } - bool bIgnore = Util::MatchFileExt(szFilename, g_pOptions->GetParIgnoreExt(), ",;") || - Util::MatchFileExt(szFilename, g_pOptions->GetExtCleanupDisk(), ",;"); - m_bHasDamagedFiles |= !bIgnore; + bool ignore = Util::MatchFileExt(filename, g_pOptions->GetParIgnoreExt(), ",;") || + Util::MatchFileExt(filename, g_pOptions->GetExtCleanupDisk(), ",;"); + m_hasDamagedFiles |= !ignore; - if (bFileExists) + if (fileExists) { PrintMessage(Message::mkWarning, "File %s has %i bad block(s) of total %i block(s)%s", - szFilename, total - available, total, bIgnore ? ", ignoring" : ""); + filename, total - available, total, ignore ? ", ignoring" : ""); } else { PrintMessage(Message::mkWarning, "File %s with %i block(s) is missing%s", - szFilename, total, bIgnore ? ", ignoring" : ""); + filename, total, ignore ? ", ignoring" : ""); } - if (!IsProcessedFile(szFilename)) + if (!IsProcessedFile(filename)) { - m_ProcessedFiles.push_back(strdup(szFilename)); + m_processedFiles.push_back(strdup(filename)); } } } @@ -1299,80 +1299,80 @@ void ParChecker::signal_done(std::string str, int available, int total) */ void ParChecker::CheckEmptyFiles() { - for (std::vector::iterator it = ((Repairer*)m_pRepairer)->sourcefiles.begin(); - it != ((Repairer*)m_pRepairer)->sourcefiles.end(); it++) + for (std::vector::iterator it = ((Repairer*)m_repairer)->sourcefiles.begin(); + it != ((Repairer*)m_repairer)->sourcefiles.end(); it++) { Par2RepairerSourceFile* sourcefile = *it; if (sourcefile && sourcefile->GetDescriptionPacket()) { // GetDescriptionPacket()->FileName() returns a temp string object, which we need to hold for a while - std::string filename = sourcefile->GetDescriptionPacket()->FileName(); - const char* szFilename = filename.c_str(); - if (!Util::EmptyStr(szFilename) && !IsProcessedFile(szFilename)) + std::string filenameObj = sourcefile->GetDescriptionPacket()->FileName(); + const char* filename = filenameObj.c_str(); + if (!Util::EmptyStr(filename) && !IsProcessedFile(filename)) { - bool bIgnore = Util::MatchFileExt(szFilename, g_pOptions->GetParIgnoreExt(), ",;") || - Util::MatchFileExt(szFilename, g_pOptions->GetExtCleanupDisk(), ",;"); - m_bHasDamagedFiles |= !bIgnore; + bool ignore = Util::MatchFileExt(filename, g_pOptions->GetParIgnoreExt(), ",;") || + Util::MatchFileExt(filename, g_pOptions->GetExtCleanupDisk(), ",;"); + m_hasDamagedFiles |= !ignore; int total = sourcefile->GetVerificationPacket() ? sourcefile->GetVerificationPacket()->BlockCount() : 0; PrintMessage(Message::mkWarning, "File %s has %i bad block(s) of total %i block(s)%s", - szFilename, total, total, bIgnore ? ", ignoring" : ""); + filename, total, total, ignore ? ", ignoring" : ""); } } else { - m_bHasDamagedFiles = true; + m_hasDamagedFiles = true; } } } void ParChecker::Cancel() { - ((Repairer*)m_pRepairer)->cancelled = true; - m_bCancelled = true; + ((Repairer*)m_repairer)->cancelled = true; + m_cancelled = true; QueueChanged(); } -void ParChecker::WriteBrokenLog(EStatus eStatus) +void ParChecker::WriteBrokenLog(EStatus status) { - char szBrokenLogName[1024]; - snprintf(szBrokenLogName, 1024, "%s%c_brokenlog.txt", m_szDestDir, (int)PATH_SEPARATOR); - szBrokenLogName[1024-1] = '\0'; + char brokenLogName[1024]; + snprintf(brokenLogName, 1024, "%s%c_brokenlog.txt", m_destDir, (int)PATH_SEPARATOR); + brokenLogName[1024-1] = '\0'; - if (eStatus != psRepairNotNeeded || Util::FileExists(szBrokenLogName)) + if (status != psRepairNotNeeded || Util::FileExists(brokenLogName)) { - FILE* file = fopen(szBrokenLogName, FOPEN_AB); + FILE* file = fopen(brokenLogName, FOPEN_AB); if (file) { - if (eStatus == psFailed) + if (status == psFailed) { - if (m_bCancelled) + if (m_cancelled) { - fprintf(file, "Repair cancelled for %s\n", m_szInfoName); + fprintf(file, "Repair cancelled for %s\n", m_infoName); } else { - fprintf(file, "Repair failed for %s: %s\n", m_szInfoName, m_szErrMsg ? m_szErrMsg : ""); + fprintf(file, "Repair failed for %s: %s\n", m_infoName, m_errMsg ? m_errMsg : ""); } } - else if (eStatus == psRepairPossible) + else if (status == psRepairPossible) { - fprintf(file, "Repair possible for %s\n", m_szInfoName); + fprintf(file, "Repair possible for %s\n", m_infoName); } - else if (eStatus == psRepaired) + else if (status == psRepaired) { - fprintf(file, "Successfully repaired %s\n", m_szInfoName); + fprintf(file, "Successfully repaired %s\n", m_infoName); } - else if (eStatus == psRepairNotNeeded) + else if (status == psRepairNotNeeded) { - fprintf(file, "Repair not needed for %s\n", m_szInfoName); + fprintf(file, "Repair not needed for %s\n", m_infoName); } fclose(file); } else { - PrintMessage(Message::mkError, "Could not open file %s", szBrokenLogName); + PrintMessage(Message::mkError, "Could not open file %s", brokenLogName); } } } @@ -1381,19 +1381,19 @@ void ParChecker::SaveSourceList() { // Buliding a list of DiskFile-objects, marked as source-files - for (std::vector::iterator it = ((Repairer*)m_pRepairer)->sourcefiles.begin(); - it != ((Repairer*)m_pRepairer)->sourcefiles.end(); it++) + for (std::vector::iterator it = ((Repairer*)m_repairer)->sourcefiles.begin(); + it != ((Repairer*)m_repairer)->sourcefiles.end(); it++) { Par2RepairerSourceFile* sourcefile = (Par2RepairerSourceFile*)*it; vector::iterator it2 = sourcefile->SourceBlocks(); for (int i = 0; i < (int)sourcefile->BlockCount(); i++, it2++) { DataBlock block = *it2; - DiskFile* pSourceFile = block.GetDiskFile(); - if (pSourceFile && - std::find(m_sourceFiles.begin(), m_sourceFiles.end(), pSourceFile) == m_sourceFiles.end()) + DiskFile* sourceFile = block.GetDiskFile(); + if (sourceFile && + std::find(m_sourceFiles.begin(), m_sourceFiles.end(), sourceFile) == m_sourceFiles.end()) { - m_sourceFiles.push_back(pSourceFile); + m_sourceFiles.push_back(sourceFile); } } } @@ -1407,24 +1407,24 @@ void ParChecker::DeleteLeftovers() for (SourceList::iterator it = m_sourceFiles.begin(); it != m_sourceFiles.end(); it++) { - DiskFile* pSourceFile = (DiskFile*)*it; + DiskFile* sourceFile = (DiskFile*)*it; - bool bFound = false; - for (std::vector::iterator it2 = ((Repairer*)m_pRepairer)->sourcefiles.begin(); - it2 != ((Repairer*)m_pRepairer)->sourcefiles.end(); it2++) + bool found = false; + for (std::vector::iterator it2 = ((Repairer*)m_repairer)->sourcefiles.begin(); + it2 != ((Repairer*)m_repairer)->sourcefiles.end(); it2++) { Par2RepairerSourceFile* sourcefile = *it2; - if (sourcefile->GetTargetFile() == pSourceFile) + if (sourcefile->GetTargetFile() == sourceFile) { - bFound = true; + found = true; break; } } - if (!bFound) + if (!found) { - PrintMessage(Message::mkInfo, "Deleting file %s", Util::BaseFileName(pSourceFile->FileName().c_str())); - remove(pSourceFile->FileName().c_str()); + PrintMessage(Message::mkInfo, "Deleting file %s", Util::BaseFileName(sourceFile->FileName().c_str())); + remove(sourceFile->FileName().c_str()); } } } @@ -1444,9 +1444,9 @@ void ParChecker::DeleteLeftovers() * The limitation can be avoided by using something more smart than "verificationhashtable.Lookup" * but in the real life all blocks have unique CRCs and the simple "Lookup" works good enough. */ -ParChecker::EFileStatus ParChecker::VerifyDataFile(void* pDiskfile, void* pSourcefile, int* pAvailableBlocks) +ParChecker::EFileStatus ParChecker::VerifyDataFile(void* diskfile, void* sourcefile, int* availableBlocks) { - if (m_eStage != ptVerifyingSources) + if (m_stage != ptVerifyingSources) { // skipping verification for repaired files, assuming the files were correctly repaired, // the only reason for incorrect files after repair are hardware errors (memory, disk), @@ -1454,160 +1454,160 @@ ParChecker::EFileStatus ParChecker::VerifyDataFile(void* pDiskfile, void* pSourc return fsSuccess; } - DiskFile* pDiskFile = (DiskFile*)pDiskfile; - Par2RepairerSourceFile* pSourceFile = (Par2RepairerSourceFile*)pSourcefile; - if (!pSourcefile || !pSourceFile->GetTargetExists()) + DiskFile* diskFile = (DiskFile*)diskfile; + Par2RepairerSourceFile* sourceFile = (Par2RepairerSourceFile*)sourcefile; + if (!sourcefile || !sourceFile->GetTargetExists()) { return fsUnknown; } - VerificationPacket* packet = pSourceFile->GetVerificationPacket(); + VerificationPacket* packet = sourceFile->GetVerificationPacket(); if (!packet) { return fsUnknown; } - std::string filename = pSourceFile->GetTargetFile()->FileName(); - const char* szFilename = filename.c_str(); + std::string filenameObj = sourceFile->GetTargetFile()->FileName(); + const char* filename = filenameObj.c_str(); - if (Util::FileSize(szFilename) == 0 && pSourceFile->BlockCount() > 0) + if (Util::FileSize(filename) == 0 && sourceFile->BlockCount() > 0) { - *pAvailableBlocks = 0; + *availableBlocks = 0; return fsFailure; } // find file status and CRC computed during download - unsigned long lDownloadCrc; + unsigned long downloadCrc; SegmentList segments; - EFileStatus eFileStatus = FindFileCrc(Util::BaseFileName(szFilename), &lDownloadCrc, &segments); + EFileStatus fileStatus = FindFileCrc(Util::BaseFileName(filename), &downloadCrc, &segments); ValidBlocks validBlocks; - if (eFileStatus == fsFailure || eFileStatus == fsUnknown) + if (fileStatus == fsFailure || fileStatus == fsUnknown) { - return eFileStatus; + return fileStatus; } - else if ((eFileStatus == fsSuccess && !VerifySuccessDataFile(pDiskfile, pSourcefile, lDownloadCrc)) || - (eFileStatus == fsPartial && !VerifyPartialDataFile(pDiskfile, pSourcefile, &segments, &validBlocks))) + else if ((fileStatus == fsSuccess && !VerifySuccessDataFile(diskfile, sourcefile, downloadCrc)) || + (fileStatus == fsPartial && !VerifyPartialDataFile(diskfile, sourcefile, &segments, &validBlocks))) { PrintMessage(Message::mkWarning, "Quick verification failed for %s file %s, performing full verification instead", - eFileStatus == fsSuccess ? "good" : "damaged", Util::BaseFileName(szFilename)); + fileStatus == fsSuccess ? "good" : "damaged", Util::BaseFileName(filename)); return fsUnknown; // let libpar2 do the full verification of the file } // attach verification blocks to the file - *pAvailableBlocks = 0; - u64 blocksize = ((Repairer*)m_pRepairer)->mainpacket->BlockSize(); + *availableBlocks = 0; + u64 blocksize = ((Repairer*)m_repairer)->mainpacket->BlockSize(); std::deque undoList; for (unsigned int i = 0; i < packet->BlockCount(); i++) { - if (eFileStatus == fsSuccess || validBlocks.at(i)) + if (fileStatus == fsSuccess || validBlocks.at(i)) { const FILEVERIFICATIONENTRY* entry = packet->VerificationEntry(i); u32 blockCrc = entry->crc; // Look for a match - const VerificationHashEntry* pHashEntry = ((Repairer*)m_pRepairer)->verificationhashtable.Lookup(blockCrc); - if (!pHashEntry || pHashEntry->SourceFile() != pSourceFile || pHashEntry->IsSet()) + const VerificationHashEntry* hashEntry = ((Repairer*)m_repairer)->verificationhashtable.Lookup(blockCrc); + if (!hashEntry || hashEntry->SourceFile() != sourceFile || hashEntry->IsSet()) { // no match found, revert back the changes made by "pHashEntry->SetBlock" for (std::deque::iterator it = undoList.begin(); it != undoList.end(); it++) { - const VerificationHashEntry* pUndoEntry = *it; - pUndoEntry->SetBlock(NULL, 0); + const VerificationHashEntry* undoEntry = *it; + undoEntry->SetBlock(NULL, 0); } return fsUnknown; } - undoList.push_back(pHashEntry); - pHashEntry->SetBlock(pDiskFile, i*blocksize); - (*pAvailableBlocks)++; + undoList.push_back(hashEntry); + hashEntry->SetBlock(diskFile, i*blocksize); + (*availableBlocks)++; } } - m_iQuickFiles++; + m_quickFiles++; PrintMessage(Message::mkDetail, "Quickly verified %s file %s", - eFileStatus == fsSuccess ? "good" : "damaged", Util::BaseFileName(szFilename)); + fileStatus == fsSuccess ? "good" : "damaged", Util::BaseFileName(filename)); - return eFileStatus; + return fileStatus; } -bool ParChecker::VerifySuccessDataFile(void* pDiskfile, void* pSourcefile, unsigned long lDownloadCrc) +bool ParChecker::VerifySuccessDataFile(void* diskfile, void* sourcefile, unsigned long downloadCrc) { - Par2RepairerSourceFile* pSourceFile = (Par2RepairerSourceFile*)pSourcefile; - u64 blocksize = ((Repairer*)m_pRepairer)->mainpacket->BlockSize(); - VerificationPacket* packet = pSourceFile->GetVerificationPacket(); + Par2RepairerSourceFile* sourceFile = (Par2RepairerSourceFile*)sourcefile; + u64 blocksize = ((Repairer*)m_repairer)->mainpacket->BlockSize(); + VerificationPacket* packet = sourceFile->GetVerificationPacket(); // extend lDownloadCrc to block size - lDownloadCrc = CRCUpdateBlock(lDownloadCrc ^ 0xFFFFFFFF, - (size_t)(blocksize * packet->BlockCount() > pSourceFile->GetTargetFile()->FileSize() ? - blocksize * packet->BlockCount() - pSourceFile->GetTargetFile()->FileSize() : 0) + downloadCrc = CRCUpdateBlock(downloadCrc ^ 0xFFFFFFFF, + (size_t)(blocksize * packet->BlockCount() > sourceFile->GetTargetFile()->FileSize() ? + blocksize * packet->BlockCount() - sourceFile->GetTargetFile()->FileSize() : 0) ) ^ 0xFFFFFFFF; - debug("Download-CRC: %.8x", lDownloadCrc); + debug("Download-CRC: %.8x", downloadCrc); // compute file CRC using CRCs of blocks - unsigned long lParCrc = 0; + unsigned long parCrc = 0; for (unsigned int i = 0; i < packet->BlockCount(); i++) { const FILEVERIFICATIONENTRY* entry = packet->VerificationEntry(i); u32 blockCrc = entry->crc; - lParCrc = i == 0 ? blockCrc : Util::Crc32Combine(lParCrc, blockCrc, (unsigned long)blocksize); + parCrc = i == 0 ? blockCrc : Util::Crc32Combine(parCrc, blockCrc, (unsigned long)blocksize); } - debug("Block-CRC: %x, filename: %s", lParCrc, Util::BaseFileName(pSourceFile->GetTargetFile()->FileName().c_str())); + debug("Block-CRC: %x, filename: %s", parCrc, Util::BaseFileName(sourceFile->GetTargetFile()->FileName().c_str())); - return lParCrc == lDownloadCrc; + return parCrc == downloadCrc; } -bool ParChecker::VerifyPartialDataFile(void* pDiskfile, void* pSourcefile, SegmentList* pSegments, ValidBlocks* pValidBlocks) +bool ParChecker::VerifyPartialDataFile(void* diskfile, void* sourcefile, SegmentList* segments, ValidBlocks* validBlocks) { - Par2RepairerSourceFile* pSourceFile = (Par2RepairerSourceFile*)pSourcefile; - VerificationPacket* packet = pSourceFile->GetVerificationPacket(); - long long blocksize = ((Repairer*)m_pRepairer)->mainpacket->BlockSize(); - std::string filename = pSourceFile->GetTargetFile()->FileName(); - const char* szFilename = filename.c_str(); - long long iFileSize = pSourceFile->GetTargetFile()->FileSize(); + Par2RepairerSourceFile* sourceFile = (Par2RepairerSourceFile*)sourcefile; + VerificationPacket* packet = sourceFile->GetVerificationPacket(); + long long blocksize = ((Repairer*)m_repairer)->mainpacket->BlockSize(); + std::string filenameObj = sourceFile->GetTargetFile()->FileName(); + const char* filename = filenameObj.c_str(); + long long fileSize = sourceFile->GetTargetFile()->FileSize(); // determine presumably valid and bad blocks based on article download status - pValidBlocks->resize(packet->BlockCount(), false); - for (int i = 0; i < (int)pValidBlocks->size(); i++) + validBlocks->resize(packet->BlockCount(), false); + for (int i = 0; i < (int)validBlocks->size(); i++) { long long blockStart = i * blocksize; - long long blockEnd = blockStart + blocksize < iFileSize - 1 ? blockStart + blocksize : iFileSize - 1; - bool bBlockOK = false; - bool bBlockEnd = false; - u64 iCurOffset = 0; - for (SegmentList::iterator it = pSegments->begin(); it != pSegments->end(); it++) + long long blockEnd = blockStart + blocksize < fileSize - 1 ? blockStart + blocksize : fileSize - 1; + bool blockOK = false; + bool blockEndFound = false; + u64 curOffset = 0; + for (SegmentList::iterator it = segments->begin(); it != segments->end(); it++) { - Segment* pSegment = *it; - if (!bBlockOK && pSegment->GetSuccess() && pSegment->GetOffset() <= blockStart && - pSegment->GetOffset() + pSegment->GetSize() >= blockStart) + Segment* segment = *it; + if (!blockOK && segment->GetSuccess() && segment->GetOffset() <= blockStart && + segment->GetOffset() + segment->GetSize() >= blockStart) { - bBlockOK = true; - iCurOffset = pSegment->GetOffset(); + blockOK = true; + curOffset = segment->GetOffset(); } - if (bBlockOK) + if (blockOK) { - if (!(pSegment->GetSuccess() && pSegment->GetOffset() == iCurOffset)) + if (!(segment->GetSuccess() && segment->GetOffset() == curOffset)) { - bBlockOK = false; + blockOK = false; break; } - if (pSegment->GetOffset() + pSegment->GetSize() >= blockEnd) + if (segment->GetOffset() + segment->GetSize() >= blockEnd) { - bBlockEnd = true; + blockEndFound = true; break; } - iCurOffset = pSegment->GetOffset() + pSegment->GetSize(); + curOffset = segment->GetOffset() + segment->GetSize(); } } - pValidBlocks->at(i) = bBlockOK && bBlockEnd; + validBlocks->at(i) = blockOK && blockEndFound; } - char szErrBuf[256]; - FILE* infile = fopen(szFilename, FOPEN_RB); + char errBuf[256]; + FILE* infile = fopen(filename, FOPEN_RB); if (!infile) { PrintMessage(Message::mkError, "Could not open file %s: %s", - szFilename, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + filename, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } // For each sequential range of presumably valid blocks: @@ -1616,45 +1616,45 @@ bool ParChecker::VerifyPartialDataFile(void* pDiskfile, void* pSourcefile, Segme // overlap - read a little bit of data from the file and calculate its CRC; // - compare two CRCs - they must match; if not - the file is more damaged than we thought - // let libpar2 do the full verification of the file in this case. - unsigned long lParCrc = 0; - int iBlockStart = -1; - pValidBlocks->push_back(false); // end marker - for (int i = 0; i < (int)pValidBlocks->size(); i++) + unsigned long parCrc = 0; + int blockStart = -1; + validBlocks->push_back(false); // end marker + for (int i = 0; i < (int)validBlocks->size(); i++) { - bool bValidBlock = pValidBlocks->at(i); - if (bValidBlock) + bool validBlock = validBlocks->at(i); + if (validBlock) { - if (iBlockStart == -1) + if (blockStart == -1) { - iBlockStart = i; + blockStart = i; } const FILEVERIFICATIONENTRY* entry = packet->VerificationEntry(i); u32 blockCrc = entry->crc; - lParCrc = iBlockStart == i ? blockCrc : Util::Crc32Combine(lParCrc, blockCrc, (unsigned long)blocksize); + parCrc = blockStart == i ? blockCrc : Util::Crc32Combine(parCrc, blockCrc, (unsigned long)blocksize); } else { - if (iBlockStart > -1) + if (blockStart > -1) { - int iBlockEnd = i - 1; - long long iBytesStart = iBlockStart * blocksize; - long long iBytesEnd = iBlockEnd * blocksize + blocksize - 1; - unsigned long lDownloadCrc = 0; - bool bOK = SmartCalcFileRangeCrc(infile, iBytesStart, - iBytesEnd < iFileSize - 1 ? iBytesEnd : iFileSize - 1, pSegments, &lDownloadCrc); - if (bOK && iBytesEnd > iFileSize - 1) + int blockEnd = i - 1; + long long bytesStart = blockStart * blocksize; + long long bytesEnd = blockEnd * blocksize + blocksize - 1; + unsigned long downloadCrc = 0; + bool ok = SmartCalcFileRangeCrc(infile, bytesStart, + bytesEnd < fileSize - 1 ? bytesEnd : fileSize - 1, segments, &downloadCrc); + if (ok && bytesEnd > fileSize - 1) { // for the last block: extend lDownloadCrc to block size - lDownloadCrc = CRCUpdateBlock(lDownloadCrc ^ 0xFFFFFFFF, (size_t)(iBytesEnd - (iFileSize - 1))) ^ 0xFFFFFFFF; + downloadCrc = CRCUpdateBlock(downloadCrc ^ 0xFFFFFFFF, (size_t)(bytesEnd - (fileSize - 1))) ^ 0xFFFFFFFF; } - if (!bOK || lDownloadCrc != lParCrc) + if (!ok || downloadCrc != parCrc) { fclose(infile); return false; } } - iBlockStart = -1; + blockStart = -1; } } @@ -1667,87 +1667,87 @@ bool ParChecker::VerifyPartialDataFile(void* pDiskfile, void* pSourcefile, Segme * Compute CRC of bytes range of file using CRCs of segments and reading some data directly * from file if necessary */ -bool ParChecker::SmartCalcFileRangeCrc(FILE* pFile, long long lStart, long long lEnd, SegmentList* pSegments, - unsigned long* pDownloadCrc) +bool ParChecker::SmartCalcFileRangeCrc(FILE* file, long long start, long long end, SegmentList* segments, + unsigned long* downloadCrcOut) { - unsigned long lDownloadCrc = 0; - bool bStarted = false; - for (SegmentList::iterator it = pSegments->begin(); it != pSegments->end(); it++) + unsigned long downloadCrc = 0; + bool started = false; + for (SegmentList::iterator it = segments->begin(); it != segments->end(); it++) { - Segment* pSegment = *it; + Segment* segment = *it; - if (!bStarted && pSegment->GetOffset() > lStart) + if (!started && segment->GetOffset() > start) { // read start of range from file - if (!DumbCalcFileRangeCrc(pFile, lStart, pSegment->GetOffset() - 1, &lDownloadCrc)) + if (!DumbCalcFileRangeCrc(file, start, segment->GetOffset() - 1, &downloadCrc)) { return false; } - if (pSegment->GetOffset() + pSegment->GetSize() >= lEnd) + if (segment->GetOffset() + segment->GetSize() >= end) { break; } - bStarted = true; + started = true; } - if (pSegment->GetOffset() >= lStart && pSegment->GetOffset() + pSegment->GetSize() <= lEnd) + if (segment->GetOffset() >= start && segment->GetOffset() + segment->GetSize() <= end) { - lDownloadCrc = !bStarted ? pSegment->GetCrc() : Util::Crc32Combine(lDownloadCrc, pSegment->GetCrc(), (unsigned long)pSegment->GetSize()); - bStarted = true; + downloadCrc = !started ? segment->GetCrc() : Util::Crc32Combine(downloadCrc, segment->GetCrc(), (unsigned long)segment->GetSize()); + started = true; } - if (pSegment->GetOffset() + pSegment->GetSize() == lEnd) + if (segment->GetOffset() + segment->GetSize() == end) { break; } - if (pSegment->GetOffset() + pSegment->GetSize() > lEnd) + if (segment->GetOffset() + segment->GetSize() > end) { // read end of range from file - unsigned long lPartialCrc = 0; - if (!DumbCalcFileRangeCrc(pFile, pSegment->GetOffset(), lEnd, &lPartialCrc)) + unsigned long partialCrc = 0; + if (!DumbCalcFileRangeCrc(file, segment->GetOffset(), end, &partialCrc)) { return false; } - lDownloadCrc = Util::Crc32Combine(lDownloadCrc, (unsigned long)lPartialCrc, (unsigned long)(lEnd - pSegment->GetOffset() + 1)); + downloadCrc = Util::Crc32Combine(downloadCrc, (unsigned long)partialCrc, (unsigned long)(end - segment->GetOffset() + 1)); break; } } - *pDownloadCrc = lDownloadCrc; + *downloadCrcOut = downloadCrc; return true; } /* * Compute CRC of bytes range of file reading the data directly from file */ -bool ParChecker::DumbCalcFileRangeCrc(FILE* pFile, long long lStart, long long lEnd, unsigned long* pDownloadCrc) +bool ParChecker::DumbCalcFileRangeCrc(FILE* file, long long start, long long end, unsigned long* downloadCrcOut) { - if (fseek(pFile, lStart, SEEK_SET)) + if (fseek(file, start, SEEK_SET)) { return false; } static const int BUFFER_SIZE = 1024 * 64; unsigned char* buffer = (unsigned char*)malloc(BUFFER_SIZE); - unsigned long lDownloadCrc = 0xFFFFFFFF; + unsigned long downloadCrc = 0xFFFFFFFF; int cnt = BUFFER_SIZE; - while (cnt == BUFFER_SIZE && lStart < lEnd) + while (cnt == BUFFER_SIZE && start < end) { - int iNeedBytes = lEnd - lStart + 1 > BUFFER_SIZE ? BUFFER_SIZE : (int)(lEnd - lStart + 1); - cnt = (int)fread(buffer, 1, iNeedBytes, pFile); - lDownloadCrc = Util::Crc32m(lDownloadCrc, buffer, cnt); - lStart += cnt; + int needBytes = end - start + 1 > BUFFER_SIZE ? BUFFER_SIZE : (int)(end - start + 1); + cnt = (int)fread(buffer, 1, needBytes, file); + downloadCrc = Util::Crc32m(downloadCrc, buffer, cnt); + start += cnt; } free(buffer); - lDownloadCrc ^= 0xFFFFFFFF; + downloadCrc ^= 0xFFFFFFFF; - *pDownloadCrc = lDownloadCrc; + *downloadCrcOut = downloadCrc; return true; } diff --git a/daemon/postprocess/ParChecker.h b/daemon/postprocess/ParChecker.h index cd24e2a8..ac22cdb1 100644 --- a/daemon/postprocess/ParChecker.h +++ b/daemon/postprocess/ParChecker.h @@ -65,17 +65,17 @@ public: class Segment { private: - bool m_bSuccess; - long long m_iOffset; - int m_iSize; - unsigned long m_lCrc; + bool m_success; + long long m_offset; + int m_size; + unsigned long m_crc; public: - Segment(bool bSuccess, long long iOffset, int iSize, unsigned long lCrc); - bool GetSuccess() { return m_bSuccess; } - long long GetOffset() { return m_iOffset; } - int GetSize() { return m_iSize; } - unsigned long GetCrc() { return m_lCrc; } + Segment(bool success, long long offset, int size, unsigned long crc); + bool GetSuccess() { return m_success; } + long long GetOffset() { return m_offset; } + int GetSize() { return m_size; } + unsigned long GetCrc() { return m_crc; } }; typedef std::deque SegmentListBase; @@ -89,17 +89,17 @@ public: class DupeSource { private: - int m_iID; - char* m_szDirectory; - int m_iUsedBlocks; + int m_id; + char* m_directory; + int m_usedBlocks; public: - DupeSource(int iID, const char* szDirectory); + DupeSource(int id, const char* directory); ~DupeSource(); - int GetID() { return m_iID; } - const char* GetDirectory() { return m_szDirectory; } - int GetUsedBlocks() { return m_iUsedBlocks; } - void SetUsedBlocks(int iUsedBlocks) { m_iUsedBlocks = iUsedBlocks; } + int GetID() { return m_id; } + const char* GetDirectory() { return m_directory; } + int GetUsedBlocks() { return m_usedBlocks; } + void SetUsedBlocks(int usedBlocks) { m_usedBlocks = usedBlocks; } }; typedef std::deque DupeSourceList; @@ -111,39 +111,39 @@ public: friend class Repairer; private: - char* m_szInfoName; - char* m_szDestDir; - char* m_szNZBName; - const char* m_szParFilename; - EStatus m_eStatus; - EStage m_eStage; + char* m_infoName; + char* m_destDir; + char* m_nzbName; + const char* m_parFilename; + EStatus m_status; + EStage m_stage; // declared as void* to prevent the including of libpar2-headers into this header-file - void* m_pRepairer; - char* m_szErrMsg; - FileList m_QueuedParFiles; - Mutex m_mutexQueuedParFiles; - bool m_bQueuedParFilesChanged; - FileList m_ProcessedFiles; - int m_iProcessedFiles; - int m_iFilesToRepair; - int m_iExtraFiles; - int m_iQuickFiles; - bool m_bVerifyingExtraFiles; - char* m_szProgressLabel; - int m_iFileProgress; - int m_iStageProgress; - bool m_bCancelled; + void* m_repairer; + char* m_errMsg; + FileList m_queuedParFiles; + Mutex m_queuedParFilesMutex; + bool m_queuedParFilesChanged; + FileList m_processedFiles; + int m_processedCount; + int m_filesToRepair; + int m_extraFiles; + int m_quickFiles; + bool m_verifyingExtraFiles; + char* m_progressLabel; + int m_fileProgress; + int m_stageProgress; + bool m_cancelled; SourceList m_sourceFiles; std::string m_lastFilename; - bool m_bHasDamagedFiles; - bool m_bParQuick; - bool m_bForceRepair; - bool m_bParFull; - DupeSourceList m_DupeSources; + bool m_hasDamagedFiles; + bool m_parQuick; + bool m_forceRepair; + bool m_parFull; + DupeSourceList m_dupeSources; void Cleanup(); EStatus RunParCheckAll(); - EStatus RunParCheck(const char* szParFilename); + EStatus RunParCheck(const char* parFilename); int PreProcessPar(); bool LoadMainParBak(); int ProcessMorePars(); @@ -151,9 +151,9 @@ private: bool AddSplittedFragments(); bool AddMissingFiles(); bool AddDupeFiles(); - bool AddExtraFiles(bool bOnlyMissing, bool bExternalDir, const char* szDirectory); - bool IsProcessedFile(const char* szFilename); - void WriteBrokenLog(EStatus eStatus); + bool AddExtraFiles(bool onlyMissing, bool externalDir, const char* directory); + bool IsProcessedFile(const char* filename); + void WriteBrokenLog(EStatus status); void SaveSourceList(); void DeleteLeftovers(); void signal_filename(std::string str); @@ -161,12 +161,12 @@ private: void signal_done(std::string str, int available, int total); // declared as void* to prevent the including of libpar2-headers into this header-file // DiskFile* pDiskfile, Par2RepairerSourceFile* pSourcefile - EFileStatus VerifyDataFile(void* pDiskfile, void* pSourcefile, int* pAvailableBlocks); - bool VerifySuccessDataFile(void* pDiskfile, void* pSourcefile, unsigned long lDownloadCrc); - bool VerifyPartialDataFile(void* pDiskfile, void* pSourcefile, SegmentList* pSegments, ValidBlocks* pValidBlocks); - bool SmartCalcFileRangeCrc(FILE* pFile, long long lStart, long long lEnd, SegmentList* pSegments, - unsigned long* pDownloadCrc); - bool DumbCalcFileRangeCrc(FILE* pFile, long long lStart, long long lEnd, unsigned long* pDownloadCrc); + EFileStatus VerifyDataFile(void* diskfile, void* sourcefile, int* availableBlocks); + bool VerifySuccessDataFile(void* diskfile, void* sourcefile, unsigned long downloadCrc); + bool VerifyPartialDataFile(void* diskfile, void* sourcefile, SegmentList* segments, ValidBlocks* validBlocks); + bool SmartCalcFileRangeCrc(FILE* file, long long start, long long end, SegmentList* segments, + unsigned long* downloadCrc); + bool DumbCalcFileRangeCrc(FILE* file, long long start, long long end, unsigned long* downloadCrc); void CheckEmptyFiles(); protected: @@ -175,40 +175,40 @@ protected: * returns true, if the files with required number of blocks were unpaused, * or false if there are no more files in queue for this collection or not enough blocks */ - virtual bool RequestMorePars(int iBlockNeeded, int* pBlockFound) = 0; + virtual bool RequestMorePars(int blockNeeded, int* blockFound) = 0; virtual void UpdateProgress() {} virtual void Completed() {} - virtual void PrintMessage(Message::EKind eKind, const char* szFormat, ...) {} - virtual void RegisterParredFile(const char* szFilename) {} - virtual bool IsParredFile(const char* szFilename) { return false; } - virtual EFileStatus FindFileCrc(const char* szFilename, unsigned long* lCrc, SegmentList* pSegments) { return fsUnknown; } - virtual void RequestDupeSources(DupeSourceList* pDupeSourceList) {} - virtual void StatDupeSources(DupeSourceList* pDupeSourceList) {} - EStage GetStage() { return m_eStage; } - const char* GetProgressLabel() { return m_szProgressLabel; } - int GetFileProgress() { return m_iFileProgress; } - int GetStageProgress() { return m_iStageProgress; } + virtual void PrintMessage(Message::EKind kind, const char* format, ...) {} + virtual void RegisterParredFile(const char* filename) {} + virtual bool IsParredFile(const char* filename) { return false; } + virtual EFileStatus FindFileCrc(const char* filename, unsigned long* crc, SegmentList* segments) { return fsUnknown; } + virtual void RequestDupeSources(DupeSourceList* dupeSourceList) {} + virtual void StatDupeSources(DupeSourceList* dupeSourceList) {} + EStage GetStage() { return m_stage; } + const char* GetProgressLabel() { return m_progressLabel; } + int GetFileProgress() { return m_fileProgress; } + int GetStageProgress() { return m_stageProgress; } public: ParChecker(); virtual ~ParChecker(); virtual void Run(); - void SetDestDir(const char* szDestDir); - const char* GetParFilename() { return m_szParFilename; } - const char* GetInfoName() { return m_szInfoName; } - void SetInfoName(const char* szInfoName); - void SetNZBName(const char* szNZBName); - void SetParQuick(bool bParQuick) { m_bParQuick = bParQuick; } - bool GetParQuick() { return m_bParQuick; } - void SetForceRepair(bool bForceRepair) { m_bForceRepair = bForceRepair; } - bool GetForceRepair() { return m_bForceRepair; } - void SetParFull(bool bParFull) { m_bParFull = bParFull; } - bool GetParFull() { return m_bParFull; } - EStatus GetStatus() { return m_eStatus; } - void AddParFile(const char* szParFilename); + void SetDestDir(const char* destDir); + const char* GetParFilename() { return m_parFilename; } + const char* GetInfoName() { return m_infoName; } + void SetInfoName(const char* infoName); + void SetNZBName(const char* nzbName); + void SetParQuick(bool parQuick) { m_parQuick = parQuick; } + bool GetParQuick() { return m_parQuick; } + void SetForceRepair(bool forceRepair) { m_forceRepair = forceRepair; } + bool GetForceRepair() { return m_forceRepair; } + void SetParFull(bool parFull) { m_parFull = parFull; } + bool GetParFull() { return m_parFull; } + EStatus GetStatus() { return m_status; } + void AddParFile(const char* parFilename); void QueueChanged(); void Cancel(); - bool GetCancelled() { return m_bCancelled; } + bool GetCancelled() { return m_cancelled; } }; #endif diff --git a/daemon/postprocess/ParCoordinator.cpp b/daemon/postprocess/ParCoordinator.cpp index 3ab43d49..d0415260 100644 --- a/daemon/postprocess/ParCoordinator.cpp +++ b/daemon/postprocess/ParCoordinator.cpp @@ -52,39 +52,39 @@ #include "Util.h" #ifndef DISABLE_PARCHECK -bool ParCoordinator::PostParChecker::RequestMorePars(int iBlockNeeded, int* pBlockFound) +bool ParCoordinator::PostParChecker::RequestMorePars(int blockNeeded, int* blockFound) { - return m_pOwner->RequestMorePars(m_pPostInfo->GetNZBInfo(), GetParFilename(), iBlockNeeded, pBlockFound); + return m_owner->RequestMorePars(m_postInfo->GetNZBInfo(), GetParFilename(), blockNeeded, blockFound); } void ParCoordinator::PostParChecker::UpdateProgress() { - m_pOwner->UpdateParCheckProgress(); + m_owner->UpdateParCheckProgress(); } -void ParCoordinator::PostParChecker::PrintMessage(Message::EKind eKind, const char* szFormat, ...) +void ParCoordinator::PostParChecker::PrintMessage(Message::EKind kind, const char* format, ...) { - char szText[1024]; + char text[1024]; va_list args; - va_start(args, szFormat); - vsnprintf(szText, 1024, szFormat, args); + va_start(args, format); + vsnprintf(text, 1024, format, args); va_end(args); - szText[1024-1] = '\0'; + text[1024-1] = '\0'; - m_pPostInfo->GetNZBInfo()->AddMessage(eKind, szText); + m_postInfo->GetNZBInfo()->AddMessage(kind, text); } -void ParCoordinator::PostParChecker::RegisterParredFile(const char* szFilename) +void ParCoordinator::PostParChecker::RegisterParredFile(const char* filename) { - m_pPostInfo->GetParredFiles()->push_back(strdup(szFilename)); + m_postInfo->GetParredFiles()->push_back(strdup(filename)); } -bool ParCoordinator::PostParChecker::IsParredFile(const char* szFilename) +bool ParCoordinator::PostParChecker::IsParredFile(const char* filename) { - for (PostInfo::ParredFiles::iterator it = m_pPostInfo->GetParredFiles()->begin(); it != m_pPostInfo->GetParredFiles()->end(); it++) + for (PostInfo::ParredFiles::iterator it = m_postInfo->GetParredFiles()->begin(); it != m_postInfo->GetParredFiles()->end(); it++) { - const char* szParredFile = *it; - if (!strcasecmp(szParredFile, szFilename)) + const char* parredFile = *it; + if (!strcasecmp(parredFile, filename)) { return true; } @@ -92,86 +92,86 @@ bool ParCoordinator::PostParChecker::IsParredFile(const char* szFilename) return false; } -ParChecker::EFileStatus ParCoordinator::PostParChecker::FindFileCrc(const char* szFilename, - unsigned long* lCrc, SegmentList* pSegments) +ParChecker::EFileStatus ParCoordinator::PostParChecker::FindFileCrc(const char* filename, + unsigned long* crc, SegmentList* segments) { - CompletedFile* pCompletedFile = NULL; + CompletedFile* completedFile = NULL; - for (CompletedFiles::iterator it = m_pPostInfo->GetNZBInfo()->GetCompletedFiles()->begin(); it != m_pPostInfo->GetNZBInfo()->GetCompletedFiles()->end(); it++) + for (CompletedFiles::iterator it = m_postInfo->GetNZBInfo()->GetCompletedFiles()->begin(); it != m_postInfo->GetNZBInfo()->GetCompletedFiles()->end(); it++) { - CompletedFile* pCompletedFile2 = *it; - if (!strcasecmp(pCompletedFile2->GetFileName(), szFilename)) + CompletedFile* completedFile2 = *it; + if (!strcasecmp(completedFile2->GetFileName(), filename)) { - pCompletedFile = pCompletedFile2; + completedFile = completedFile2; break; } } - if (!pCompletedFile) + if (!completedFile) { return ParChecker::fsUnknown; } - debug("Found completed file: %s, CRC: %.8x, Status: %i", Util::BaseFileName(pCompletedFile->GetFileName()), pCompletedFile->GetCrc(), (int)pCompletedFile->GetStatus()); + debug("Found completed file: %s, CRC: %.8x, Status: %i", Util::BaseFileName(completedFile->GetFileName()), completedFile->GetCrc(), (int)completedFile->GetStatus()); - *lCrc = pCompletedFile->GetCrc(); + *crc = completedFile->GetCrc(); - if (pCompletedFile->GetStatus() == CompletedFile::cfPartial && pCompletedFile->GetID() > 0 && - !m_pPostInfo->GetNZBInfo()->GetReprocess()) + if (completedFile->GetStatus() == CompletedFile::cfPartial && completedFile->GetID() > 0 && + !m_postInfo->GetNZBInfo()->GetReprocess()) { - FileInfo* pTmpFileInfo = new FileInfo(pCompletedFile->GetID()); + FileInfo* tmpFileInfo = new FileInfo(completedFile->GetID()); - if (!g_pDiskState->LoadFileState(pTmpFileInfo, NULL, true)) + if (!g_pDiskState->LoadFileState(tmpFileInfo, NULL, true)) { - delete pTmpFileInfo; + delete tmpFileInfo; return ParChecker::fsUnknown; } - for (FileInfo::Articles::iterator it = pTmpFileInfo->GetArticles()->begin(); it != pTmpFileInfo->GetArticles()->end(); it++) + for (FileInfo::Articles::iterator it = tmpFileInfo->GetArticles()->begin(); it != tmpFileInfo->GetArticles()->end(); it++) { ArticleInfo* pa = *it; - ParChecker::Segment* pSegment = new Segment(pa->GetStatus() == ArticleInfo::aiFinished, + ParChecker::Segment* segment = new Segment(pa->GetStatus() == ArticleInfo::aiFinished, pa->GetSegmentOffset(), pa->GetSegmentSize(), pa->GetCrc()); - pSegments->push_back(pSegment); + segments->push_back(segment); } - delete pTmpFileInfo; + delete tmpFileInfo; } - return pCompletedFile->GetStatus() == CompletedFile::cfSuccess ? ParChecker::fsSuccess : - pCompletedFile->GetStatus() == CompletedFile::cfFailure && - !m_pPostInfo->GetNZBInfo()->GetReprocess() ? ParChecker::fsFailure : - pCompletedFile->GetStatus() == CompletedFile::cfPartial && pSegments->size() > 0 && - !m_pPostInfo->GetNZBInfo()->GetReprocess()? ParChecker::fsPartial : + return completedFile->GetStatus() == CompletedFile::cfSuccess ? ParChecker::fsSuccess : + completedFile->GetStatus() == CompletedFile::cfFailure && + !m_postInfo->GetNZBInfo()->GetReprocess() ? ParChecker::fsFailure : + completedFile->GetStatus() == CompletedFile::cfPartial && segments->size() > 0 && + !m_postInfo->GetNZBInfo()->GetReprocess()? ParChecker::fsPartial : ParChecker::fsUnknown; } -void ParCoordinator::PostParChecker::RequestDupeSources(DupeSourceList* pDupeSourceList) +void ParCoordinator::PostParChecker::RequestDupeSources(DupeSourceList* dupeSourceList) { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); NZBList dupeList; - g_pDupeCoordinator->ListHistoryDupes(pDownloadQueue, m_pPostInfo->GetNZBInfo(), &dupeList); + g_pDupeCoordinator->ListHistoryDupes(downloadQueue, m_postInfo->GetNZBInfo(), &dupeList); if (!dupeList.empty()) { - PostDupeMatcher dupeMatcher(m_pPostInfo); - PrintMessage(Message::mkInfo, "Checking %s for dupe scan usability", m_pPostInfo->GetNZBInfo()->GetName()); - bool bSizeComparisonPossible = dupeMatcher.Prepare(); + PostDupeMatcher dupeMatcher(m_postInfo); + PrintMessage(Message::mkInfo, "Checking %s for dupe scan usability", m_postInfo->GetNZBInfo()->GetName()); + bool sizeComparisonPossible = dupeMatcher.Prepare(); for (NZBList::iterator it = dupeList.begin(); it != dupeList.end(); it++) { - NZBInfo* pDupeNZBInfo = *it; - if (bSizeComparisonPossible) + NZBInfo* dupeNzbInfo = *it; + if (sizeComparisonPossible) { - PrintMessage(Message::mkInfo, "Checking %s for dupe scan usability", Util::BaseFileName(pDupeNZBInfo->GetDestDir())); + PrintMessage(Message::mkInfo, "Checking %s for dupe scan usability", Util::BaseFileName(dupeNzbInfo->GetDestDir())); } - bool bUseDupe = !bSizeComparisonPossible || dupeMatcher.MatchDupeContent(pDupeNZBInfo->GetDestDir()); - if (bUseDupe) + bool useDupe = !sizeComparisonPossible || dupeMatcher.MatchDupeContent(dupeNzbInfo->GetDestDir()); + if (useDupe) { - PrintMessage(Message::mkInfo, "Adding %s to dupe scan sources", Util::BaseFileName(pDupeNZBInfo->GetDestDir())); - pDupeSourceList->push_back(new ParChecker::DupeSource(pDupeNZBInfo->GetID(), pDupeNZBInfo->GetDestDir())); + PrintMessage(Message::mkInfo, "Adding %s to dupe scan sources", Util::BaseFileName(dupeNzbInfo->GetDestDir())); + dupeSourceList->push_back(new ParChecker::DupeSource(dupeNzbInfo->GetID(), dupeNzbInfo->GetDestDir())); } } - if (pDupeSourceList->empty()) + if (dupeSourceList->empty()) { PrintMessage(Message::mkInfo, "No usable dupe scan sources found"); } @@ -180,82 +180,82 @@ void ParCoordinator::PostParChecker::RequestDupeSources(DupeSourceList* pDupeSou DownloadQueue::Unlock(); } -void ParCoordinator::PostParChecker::StatDupeSources(DupeSourceList* pDupeSourceList) +void ParCoordinator::PostParChecker::StatDupeSources(DupeSourceList* dupeSourceList) { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - int iTotalExtraParBlocks = 0; - for (DupeSourceList::iterator it = pDupeSourceList->begin(); it != pDupeSourceList->end(); it++) + int totalExtraParBlocks = 0; + for (DupeSourceList::iterator it = dupeSourceList->begin(); it != dupeSourceList->end(); it++) { - DupeSource* pDupeSource = *it; - if (pDupeSource->GetUsedBlocks() > 0) + DupeSource* dupeSource = *it; + if (dupeSource->GetUsedBlocks() > 0) { - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetID() == pDupeSource->GetID()) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetID() == dupeSource->GetID()) { - pHistoryInfo->GetNZBInfo()->SetExtraParBlocks(pHistoryInfo->GetNZBInfo()->GetExtraParBlocks() - pDupeSource->GetUsedBlocks()); + historyInfo->GetNZBInfo()->SetExtraParBlocks(historyInfo->GetNZBInfo()->GetExtraParBlocks() - dupeSource->GetUsedBlocks()); } } } - iTotalExtraParBlocks += pDupeSource->GetUsedBlocks(); + totalExtraParBlocks += dupeSource->GetUsedBlocks(); } - m_pPostInfo->GetNZBInfo()->SetExtraParBlocks(m_pPostInfo->GetNZBInfo()->GetExtraParBlocks() + iTotalExtraParBlocks); + m_postInfo->GetNZBInfo()->SetExtraParBlocks(m_postInfo->GetNZBInfo()->GetExtraParBlocks() + totalExtraParBlocks); DownloadQueue::Unlock(); } void ParCoordinator::PostParRenamer::UpdateProgress() { - m_pOwner->UpdateParRenameProgress(); + m_owner->UpdateParRenameProgress(); } -void ParCoordinator::PostParRenamer::PrintMessage(Message::EKind eKind, const char* szFormat, ...) +void ParCoordinator::PostParRenamer::PrintMessage(Message::EKind kind, const char* format, ...) { - char szText[1024]; + char text[1024]; va_list args; - va_start(args, szFormat); - vsnprintf(szText, 1024, szFormat, args); + va_start(args, format); + vsnprintf(text, 1024, format, args); va_end(args); - szText[1024-1] = '\0'; + text[1024-1] = '\0'; - m_pPostInfo->GetNZBInfo()->AddMessage(eKind, szText); + m_postInfo->GetNZBInfo()->AddMessage(kind, text); } -void ParCoordinator::PostParRenamer::RegisterParredFile(const char* szFilename) +void ParCoordinator::PostParRenamer::RegisterParredFile(const char* filename) { - m_pPostInfo->GetParredFiles()->push_back(strdup(szFilename)); + m_postInfo->GetParredFiles()->push_back(strdup(filename)); } /** * Update file name in the CompletedFiles-list of NZBInfo */ -void ParCoordinator::PostParRenamer::RegisterRenamedFile(const char* szOldFilename, const char* szNewFileName) +void ParCoordinator::PostParRenamer::RegisterRenamedFile(const char* oldFilename, const char* newFileName) { - for (CompletedFiles::iterator it = m_pPostInfo->GetNZBInfo()->GetCompletedFiles()->begin(); it != m_pPostInfo->GetNZBInfo()->GetCompletedFiles()->end(); it++) + for (CompletedFiles::iterator it = m_postInfo->GetNZBInfo()->GetCompletedFiles()->begin(); it != m_postInfo->GetNZBInfo()->GetCompletedFiles()->end(); it++) { - CompletedFile* pCompletedFile = *it; - if (!strcasecmp(pCompletedFile->GetFileName(), szOldFilename)) + CompletedFile* completedFile = *it; + if (!strcasecmp(completedFile->GetFileName(), oldFilename)) { - pCompletedFile->SetFileName(szNewFileName); + completedFile->SetFileName(newFileName); break; } } } -void ParCoordinator::PostDupeMatcher::PrintMessage(Message::EKind eKind, const char* szFormat, ...) +void ParCoordinator::PostDupeMatcher::PrintMessage(Message::EKind kind, const char* format, ...) { - char szText[1024]; + char text[1024]; va_list args; - va_start(args, szFormat); - vsnprintf(szText, 1024, szFormat, args); + va_start(args, format); + vsnprintf(text, 1024, format, args); va_end(args); - szText[1024-1] = '\0'; + text[1024-1] = '\0'; - m_pPostInfo->GetNZBInfo()->AddMessage(eKind, szText); + m_postInfo->GetNZBInfo()->AddMessage(kind, text); } #endif @@ -265,9 +265,9 @@ ParCoordinator::ParCoordinator() debug("Creating ParCoordinator"); #ifndef DISABLE_PARCHECK - m_bStopped = false; - m_ParChecker.m_pOwner = this; - m_ParRenamer.m_pOwner = this; + m_stopped = false; + m_parChecker.m_owner = this; + m_parRenamer.m_owner = this; #endif } @@ -281,31 +281,31 @@ void ParCoordinator::Stop() { debug("Stopping ParCoordinator"); - m_bStopped = true; + m_stopped = true; - if (m_ParChecker.IsRunning()) + if (m_parChecker.IsRunning()) { - m_ParChecker.Stop(); - int iMSecWait = 5000; - while (m_ParChecker.IsRunning() && iMSecWait > 0) + m_parChecker.Stop(); + int mSecWait = 5000; + while (m_parChecker.IsRunning() && mSecWait > 0) { usleep(50 * 1000); - iMSecWait -= 50; + mSecWait -= 50; } - if (m_ParChecker.IsRunning()) + if (m_parChecker.IsRunning()) { - warn("Terminating par-check for %s", m_ParChecker.GetInfoName()); - m_ParChecker.Kill(); + warn("Terminating par-check for %s", m_parChecker.GetInfoName()); + m_parChecker.Kill(); } } } #endif -void ParCoordinator::PausePars(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void ParCoordinator::PausePars(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { debug("ParCoordinator: Pausing pars"); - pDownloadQueue->EditEntry(pNZBInfo->GetID(), + downloadQueue->EditEntry(nzbInfo->GetID(), DownloadQueue::eaGroupPauseExtraPars, 0, NULL); } @@ -314,63 +314,63 @@ void ParCoordinator::PausePars(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) /** * DownloadQueue must be locked prior to call of this function. */ -void ParCoordinator::StartParCheckJob(PostInfo* pPostInfo) +void ParCoordinator::StartParCheckJob(PostInfo* postInfo) { - m_eCurrentJob = jkParCheck; - m_ParChecker.SetPostInfo(pPostInfo); - m_ParChecker.SetDestDir(pPostInfo->GetNZBInfo()->GetDestDir()); - m_ParChecker.SetNZBName(pPostInfo->GetNZBInfo()->GetName()); - m_ParChecker.SetParTime(time(NULL)); - m_ParChecker.SetDownloadSec(pPostInfo->GetNZBInfo()->GetDownloadSec()); - m_ParChecker.SetParQuick(g_pOptions->GetParQuick() && !pPostInfo->GetForceParFull()); - m_ParChecker.SetForceRepair(pPostInfo->GetForceRepair()); - m_ParChecker.PrintMessage(Message::mkInfo, "Checking pars for %s", pPostInfo->GetNZBInfo()->GetName()); - pPostInfo->SetWorking(true); - m_ParChecker.Start(); + m_currentJob = jkParCheck; + m_parChecker.SetPostInfo(postInfo); + m_parChecker.SetDestDir(postInfo->GetNZBInfo()->GetDestDir()); + m_parChecker.SetNZBName(postInfo->GetNZBInfo()->GetName()); + m_parChecker.SetParTime(time(NULL)); + m_parChecker.SetDownloadSec(postInfo->GetNZBInfo()->GetDownloadSec()); + m_parChecker.SetParQuick(g_pOptions->GetParQuick() && !postInfo->GetForceParFull()); + m_parChecker.SetForceRepair(postInfo->GetForceRepair()); + m_parChecker.PrintMessage(Message::mkInfo, "Checking pars for %s", postInfo->GetNZBInfo()->GetName()); + postInfo->SetWorking(true); + m_parChecker.Start(); } /** * DownloadQueue must be locked prior to call of this function. */ -void ParCoordinator::StartParRenameJob(PostInfo* pPostInfo) +void ParCoordinator::StartParRenameJob(PostInfo* postInfo) { - const char* szDestDir = pPostInfo->GetNZBInfo()->GetDestDir(); + const char* destDir = postInfo->GetNZBInfo()->GetDestDir(); - char szFinalDir[1024]; - if (pPostInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usSuccess) + char finalDir[1024]; + if (postInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usSuccess) { - pPostInfo->GetNZBInfo()->BuildFinalDirName(szFinalDir, 1024); - szFinalDir[1024-1] = '\0'; - szDestDir = szFinalDir; + postInfo->GetNZBInfo()->BuildFinalDirName(finalDir, 1024); + finalDir[1024-1] = '\0'; + destDir = finalDir; } - m_eCurrentJob = jkParRename; - m_ParRenamer.SetPostInfo(pPostInfo); - m_ParRenamer.SetDestDir(szDestDir); - m_ParRenamer.SetInfoName(pPostInfo->GetNZBInfo()->GetName()); - m_ParRenamer.SetDetectMissing(pPostInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usNone); - m_ParRenamer.PrintMessage(Message::mkInfo, "Checking renamed files for %s", pPostInfo->GetNZBInfo()->GetName()); - pPostInfo->SetWorking(true); - m_ParRenamer.Start(); + m_currentJob = jkParRename; + m_parRenamer.SetPostInfo(postInfo); + m_parRenamer.SetDestDir(destDir); + m_parRenamer.SetInfoName(postInfo->GetNZBInfo()->GetName()); + m_parRenamer.SetDetectMissing(postInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usNone); + m_parRenamer.PrintMessage(Message::mkInfo, "Checking renamed files for %s", postInfo->GetNZBInfo()->GetName()); + postInfo->SetWorking(true); + m_parRenamer.Start(); } bool ParCoordinator::Cancel() { - if (m_eCurrentJob == jkParCheck) + if (m_currentJob == jkParCheck) { - if (!m_ParChecker.GetCancelled()) + if (!m_parChecker.GetCancelled()) { - debug("Cancelling par-repair for %s", m_ParChecker.GetInfoName()); - m_ParChecker.Cancel(); + debug("Cancelling par-repair for %s", m_parChecker.GetInfoName()); + m_parChecker.Cancel(); return true; } } - else if (m_eCurrentJob == jkParRename) + else if (m_currentJob == jkParRename) { - if (!m_ParRenamer.GetCancelled()) + if (!m_parRenamer.GetCancelled()) { - debug("Cancelling par-rename for %s", m_ParRenamer.GetInfoName()); - m_ParRenamer.Cancel(); + debug("Cancelling par-rename for %s", m_parRenamer.GetInfoName()); + m_parRenamer.Cancel(); return true; } } @@ -380,59 +380,59 @@ bool ParCoordinator::Cancel() /** * DownloadQueue must be locked prior to call of this function. */ -bool ParCoordinator::AddPar(FileInfo* pFileInfo, bool bDeleted) +bool ParCoordinator::AddPar(FileInfo* fileInfo, bool deleted) { - bool bSameCollection = m_ParChecker.IsRunning() && - pFileInfo->GetNZBInfo() == m_ParChecker.GetPostInfo()->GetNZBInfo(); - if (bSameCollection && !bDeleted) + bool sameCollection = m_parChecker.IsRunning() && + fileInfo->GetNZBInfo() == m_parChecker.GetPostInfo()->GetNZBInfo(); + if (sameCollection && !deleted) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", pFileInfo->GetNZBInfo()->GetDestDir(), (int)PATH_SEPARATOR, pFileInfo->GetFilename()); - szFullFilename[1024-1] = '\0'; - m_ParChecker.AddParFile(szFullFilename); + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", fileInfo->GetNZBInfo()->GetDestDir(), (int)PATH_SEPARATOR, fileInfo->GetFilename()); + fullFilename[1024-1] = '\0'; + m_parChecker.AddParFile(fullFilename); } else { - m_ParChecker.QueueChanged(); + m_parChecker.QueueChanged(); } - return bSameCollection; + return sameCollection; } void ParCoordinator::ParCheckCompleted() { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - PostInfo* pPostInfo = m_ParChecker.GetPostInfo(); + PostInfo* postInfo = m_parChecker.GetPostInfo(); // Update ParStatus (accumulate result) - if ((m_ParChecker.GetStatus() == ParChecker::psRepaired || - m_ParChecker.GetStatus() == ParChecker::psRepairNotNeeded) && - pPostInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped) + if ((m_parChecker.GetStatus() == ParChecker::psRepaired || + m_parChecker.GetStatus() == ParChecker::psRepairNotNeeded) && + postInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped) { - pPostInfo->GetNZBInfo()->SetParStatus(NZBInfo::psSuccess); - pPostInfo->SetParRepaired(m_ParChecker.GetStatus() == ParChecker::psRepaired); + postInfo->GetNZBInfo()->SetParStatus(NZBInfo::psSuccess); + postInfo->SetParRepaired(m_parChecker.GetStatus() == ParChecker::psRepaired); } - else if (m_ParChecker.GetStatus() == ParChecker::psRepairPossible && - pPostInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psFailure) + else if (m_parChecker.GetStatus() == ParChecker::psRepairPossible && + postInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psFailure) { - pPostInfo->GetNZBInfo()->SetParStatus(NZBInfo::psRepairPossible); + postInfo->GetNZBInfo()->SetParStatus(NZBInfo::psRepairPossible); } else { - pPostInfo->GetNZBInfo()->SetParStatus(NZBInfo::psFailure); + postInfo->GetNZBInfo()->SetParStatus(NZBInfo::psFailure); } - int iWaitTime = pPostInfo->GetNZBInfo()->GetDownloadSec() - m_ParChecker.GetDownloadSec(); - pPostInfo->SetStartTime(pPostInfo->GetStartTime() + (time_t)iWaitTime); - int iParSec = (int)(time(NULL) - m_ParChecker.GetParTime()) - iWaitTime; - pPostInfo->GetNZBInfo()->SetParSec(pPostInfo->GetNZBInfo()->GetParSec() + iParSec); + int waitTime = postInfo->GetNZBInfo()->GetDownloadSec() - m_parChecker.GetDownloadSec(); + postInfo->SetStartTime(postInfo->GetStartTime() + (time_t)waitTime); + int parSec = (int)(time(NULL) - m_parChecker.GetParTime()) - waitTime; + postInfo->GetNZBInfo()->SetParSec(postInfo->GetNZBInfo()->GetParSec() + parSec); - pPostInfo->GetNZBInfo()->SetParFull(m_ParChecker.GetParFull()); + postInfo->GetNZBInfo()->SetParFull(m_parChecker.GetParFull()); - pPostInfo->SetWorking(false); - pPostInfo->SetStage(PostInfo::ptQueued); + postInfo->SetWorking(false); + postInfo->SetStage(PostInfo::ptQueued); - pDownloadQueue->Save(); + downloadQueue->Save(); DownloadQueue::Unlock(); } @@ -444,57 +444,57 @@ void ParCoordinator::ParCheckCompleted() * special case: returns true if there are any unpaused par2-files in the queue regardless * of the amount of blocks; this is to keep par-checker wait for download completion. */ -bool ParCoordinator::RequestMorePars(NZBInfo* pNZBInfo, const char* szParFilename, int iBlockNeeded, int* pBlockFound) +bool ParCoordinator::RequestMorePars(NZBInfo* nzbInfo, const char* parFilename, int blockNeeded, int* blockFoundOut) { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); Blocks blocks; blocks.clear(); - int iBlockFound = 0; - int iCurBlockFound = 0; + int blockFound = 0; + int curBlockFound = 0; - FindPars(pDownloadQueue, pNZBInfo, szParFilename, &blocks, true, true, &iCurBlockFound); - iBlockFound += iCurBlockFound; - if (iBlockFound < iBlockNeeded) + FindPars(downloadQueue, nzbInfo, parFilename, &blocks, true, true, &curBlockFound); + blockFound += curBlockFound; + if (blockFound < blockNeeded) { - FindPars(pDownloadQueue, pNZBInfo, szParFilename, &blocks, true, false, &iCurBlockFound); - iBlockFound += iCurBlockFound; + FindPars(downloadQueue, nzbInfo, parFilename, &blocks, true, false, &curBlockFound); + blockFound += curBlockFound; } - if (iBlockFound < iBlockNeeded) + if (blockFound < blockNeeded) { - FindPars(pDownloadQueue, pNZBInfo, szParFilename, &blocks, false, false, &iCurBlockFound); - iBlockFound += iCurBlockFound; + FindPars(downloadQueue, nzbInfo, parFilename, &blocks, false, false, &curBlockFound); + blockFound += curBlockFound; } - if (iBlockFound >= iBlockNeeded) + if (blockFound >= blockNeeded) { // 1. first unpause all files with par-blocks less or equal iBlockNeeded // starting from the file with max block count. // if par-collection was built exponentially and all par-files present, // this step selects par-files with exact number of blocks we need. - while (iBlockNeeded > 0) + while (blockNeeded > 0) { - BlockInfo* pBestBlockInfo = NULL; + BlockInfo* bestBlockInfo = NULL; for (Blocks::iterator it = blocks.begin(); it != blocks.end(); it++) { - BlockInfo* pBlockInfo = *it; - if (pBlockInfo->m_iBlockCount <= iBlockNeeded && - (!pBestBlockInfo || pBestBlockInfo->m_iBlockCount < pBlockInfo->m_iBlockCount)) + BlockInfo* blockInfo = *it; + if (blockInfo->m_blockCount <= blockNeeded && + (!bestBlockInfo || bestBlockInfo->m_blockCount < blockInfo->m_blockCount)) { - pBestBlockInfo = pBlockInfo; + bestBlockInfo = blockInfo; } } - if (pBestBlockInfo) + if (bestBlockInfo) { - if (pBestBlockInfo->m_pFileInfo->GetPaused()) + if (bestBlockInfo->m_fileInfo->GetPaused()) { - m_ParChecker.PrintMessage(Message::mkInfo, "Unpausing %s%c%s for par-recovery", pNZBInfo->GetName(), (int)PATH_SEPARATOR, pBestBlockInfo->m_pFileInfo->GetFilename()); - pBestBlockInfo->m_pFileInfo->SetPaused(false); - pBestBlockInfo->m_pFileInfo->SetExtraPriority(true); + m_parChecker.PrintMessage(Message::mkInfo, "Unpausing %s%c%s for par-recovery", nzbInfo->GetName(), (int)PATH_SEPARATOR, bestBlockInfo->m_fileInfo->GetFilename()); + bestBlockInfo->m_fileInfo->SetPaused(false); + bestBlockInfo->m_fileInfo->SetExtraPriority(true); } - iBlockNeeded -= pBestBlockInfo->m_iBlockCount; - blocks.remove(pBestBlockInfo); - delete pBestBlockInfo; + blockNeeded -= bestBlockInfo->m_blockCount; + blocks.remove(bestBlockInfo); + delete bestBlockInfo; } else { @@ -507,35 +507,35 @@ bool ParCoordinator::RequestMorePars(NZBInfo* pNZBInfo, const char* szParFilenam // or not all par-files present (or some of them were corrupted) // this step is not optimal, but we hope, that the first step will work good // in most cases and we will not need the second step often - while (iBlockNeeded > 0) + while (blockNeeded > 0) { - BlockInfo* pBlockInfo = blocks.front(); - if (pBlockInfo->m_pFileInfo->GetPaused()) + BlockInfo* blockInfo = blocks.front(); + if (blockInfo->m_fileInfo->GetPaused()) { - m_ParChecker.PrintMessage(Message::mkInfo, "Unpausing %s%c%s for par-recovery", pNZBInfo->GetName(), (int)PATH_SEPARATOR, pBlockInfo->m_pFileInfo->GetFilename()); - pBlockInfo->m_pFileInfo->SetPaused(false); - pBlockInfo->m_pFileInfo->SetExtraPriority(true); + m_parChecker.PrintMessage(Message::mkInfo, "Unpausing %s%c%s for par-recovery", nzbInfo->GetName(), (int)PATH_SEPARATOR, blockInfo->m_fileInfo->GetFilename()); + blockInfo->m_fileInfo->SetPaused(false); + blockInfo->m_fileInfo->SetExtraPriority(true); } - iBlockNeeded -= pBlockInfo->m_iBlockCount; + blockNeeded -= blockInfo->m_blockCount; } } - bool bHasUnpausedParFiles = false; - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + bool hasUnpausedParFiles = false; + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - if (pFileInfo->GetParFile() && !pFileInfo->GetPaused()) + FileInfo* fileInfo = *it; + if (fileInfo->GetParFile() && !fileInfo->GetPaused()) { - bHasUnpausedParFiles = true; + hasUnpausedParFiles = true; break; } } DownloadQueue::Unlock(); - if (pBlockFound) + if (blockFoundOut) { - *pBlockFound = iBlockFound; + *blockFoundOut = blockFound; } for (Blocks::iterator it = blocks.begin(); it != blocks.end(); it++) @@ -544,75 +544,75 @@ bool ParCoordinator::RequestMorePars(NZBInfo* pNZBInfo, const char* szParFilenam } blocks.clear(); - bool bOK = iBlockNeeded <= 0 || bHasUnpausedParFiles; + bool ok = blockNeeded <= 0 || hasUnpausedParFiles; - return bOK; + return ok; } -void ParCoordinator::FindPars(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szParFilename, - Blocks* pBlocks, bool bStrictParName, bool bExactParName, int* pBlockFound) +void ParCoordinator::FindPars(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* parFilename, + Blocks* blocks, bool strictParName, bool exactParName, int* blockFound) { - *pBlockFound = 0; + *blockFound = 0; // extract base name from m_szParFilename (trim .par2-extension and possible .vol-part) - char* szBaseParFilename = Util::BaseFileName(szParFilename); - char szMainBaseFilename[1024]; - int iMainBaseLen = 0; - if (!ParParser::ParseParFilename(szBaseParFilename, &iMainBaseLen, NULL)) + char* baseParFilename = Util::BaseFileName(parFilename); + char mainBaseFilename[1024]; + int mainBaseLen = 0; + if (!ParParser::ParseParFilename(baseParFilename, &mainBaseLen, NULL)) { // should not happen - pNZBInfo->PrintMessage(Message::mkError, "Internal error: could not parse filename %s", szBaseParFilename); + nzbInfo->PrintMessage(Message::mkError, "Internal error: could not parse filename %s", baseParFilename); return; } - int maxlen = iMainBaseLen < 1024 ? iMainBaseLen : 1024 - 1; - strncpy(szMainBaseFilename, szBaseParFilename, maxlen); - szMainBaseFilename[maxlen] = '\0'; - for (char* p = szMainBaseFilename; *p; p++) *p = tolower(*p); // convert string to lowercase + int maxlen = mainBaseLen < 1024 ? mainBaseLen : 1024 - 1; + strncpy(mainBaseFilename, baseParFilename, maxlen); + mainBaseFilename[maxlen] = '\0'; + for (char* p = mainBaseFilename; *p; p++) *p = tolower(*p); // convert string to lowercase - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - int iBlocks = 0; - if (ParParser::ParseParFilename(pFileInfo->GetFilename(), NULL, &iBlocks) && - iBlocks > 0) + FileInfo* fileInfo = *it; + int blockCount = 0; + if (ParParser::ParseParFilename(fileInfo->GetFilename(), NULL, &blockCount) && + blockCount > 0) { - bool bUseFile = true; + bool useFile = true; - if (bExactParName) + if (exactParName) { - bUseFile = ParParser::SameParCollection(pFileInfo->GetFilename(), Util::BaseFileName(szParFilename)); + useFile = ParParser::SameParCollection(fileInfo->GetFilename(), Util::BaseFileName(parFilename)); } - else if (bStrictParName) + else if (strictParName) { // the pFileInfo->GetFilename() may be not confirmed and may contain // additional texts if Subject could not be parsed correctly - char szLoFileName[1024]; - strncpy(szLoFileName, pFileInfo->GetFilename(), 1024); - szLoFileName[1024-1] = '\0'; - for (char* p = szLoFileName; *p; p++) *p = tolower(*p); // convert string to lowercase + char loFileName[1024]; + strncpy(loFileName, fileInfo->GetFilename(), 1024); + loFileName[1024-1] = '\0'; + for (char* p = loFileName; *p; p++) *p = tolower(*p); // convert string to lowercase - char szCandidateFileName[1024]; - snprintf(szCandidateFileName, 1024, "%s.par2", szMainBaseFilename); - szCandidateFileName[1024-1] = '\0'; - if (!strstr(szLoFileName, szCandidateFileName)) + char candidateFileName[1024]; + snprintf(candidateFileName, 1024, "%s.par2", mainBaseFilename); + candidateFileName[1024-1] = '\0'; + if (!strstr(loFileName, candidateFileName)) { - snprintf(szCandidateFileName, 1024, "%s.vol", szMainBaseFilename); - szCandidateFileName[1024-1] = '\0'; - bUseFile = strstr(szLoFileName, szCandidateFileName); + snprintf(candidateFileName, 1024, "%s.vol", mainBaseFilename); + candidateFileName[1024-1] = '\0'; + useFile = strstr(loFileName, candidateFileName); } } - bool bAlreadyAdded = false; + bool alreadyAdded = false; // check if file is not in the list already - if (bUseFile) + if (useFile) { - for (Blocks::iterator it = pBlocks->begin(); it != pBlocks->end(); it++) + for (Blocks::iterator it = blocks->begin(); it != blocks->end(); it++) { - BlockInfo* pBlockInfo = *it; - if (pBlockInfo->m_pFileInfo == pFileInfo) + BlockInfo* blockInfo = *it; + if (blockInfo->m_fileInfo == fileInfo) { - bAlreadyAdded = true; + alreadyAdded = true; break; } } @@ -621,13 +621,13 @@ void ParCoordinator::FindPars(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, // if it is a par2-file with blocks and it was from the same NZB-request // and it belongs to the same file collection (same base name), // then OK, we can use it - if (bUseFile && !bAlreadyAdded) + if (useFile && !alreadyAdded) { - BlockInfo* pBlockInfo = new BlockInfo(); - pBlockInfo->m_pFileInfo = pFileInfo; - pBlockInfo->m_iBlockCount = iBlocks; - pBlocks->push_back(pBlockInfo); - *pBlockFound += iBlocks; + BlockInfo* blockInfo = new BlockInfo(); + blockInfo->m_fileInfo = fileInfo; + blockInfo->m_blockCount = blockCount; + blocks->push_back(blockInfo); + *blockFound += blockCount; } } } @@ -637,96 +637,96 @@ void ParCoordinator::UpdateParCheckProgress() { DownloadQueue::Lock(); - PostInfo* pPostInfo = m_ParChecker.GetPostInfo(); - if (m_ParChecker.GetFileProgress() == 0) + PostInfo* postInfo = m_parChecker.GetPostInfo(); + if (m_parChecker.GetFileProgress() == 0) { - pPostInfo->SetProgressLabel(m_ParChecker.GetProgressLabel()); + postInfo->SetProgressLabel(m_parChecker.GetProgressLabel()); } - pPostInfo->SetFileProgress(m_ParChecker.GetFileProgress()); - pPostInfo->SetStageProgress(m_ParChecker.GetStageProgress()); + postInfo->SetFileProgress(m_parChecker.GetFileProgress()); + postInfo->SetStageProgress(m_parChecker.GetStageProgress()); PostInfo::EStage StageKind[] = { PostInfo::ptLoadingPars, PostInfo::ptVerifyingSources, PostInfo::ptRepairing, PostInfo::ptVerifyingRepaired }; - PostInfo::EStage eStage = StageKind[m_ParChecker.GetStage()]; - time_t tCurrent = time(NULL); + PostInfo::EStage stage = StageKind[m_parChecker.GetStage()]; + time_t current = time(NULL); - if (pPostInfo->GetStage() != eStage) + if (postInfo->GetStage() != stage) { - pPostInfo->SetStage(eStage); - pPostInfo->SetStageTime(tCurrent); - if (pPostInfo->GetStage() == PostInfo::ptRepairing) + postInfo->SetStage(stage); + postInfo->SetStageTime(current); + if (postInfo->GetStage() == PostInfo::ptRepairing) { - m_ParChecker.SetRepairTime(tCurrent); + m_parChecker.SetRepairTime(current); } - else if (pPostInfo->GetStage() == PostInfo::ptVerifyingRepaired) + else if (postInfo->GetStage() == PostInfo::ptVerifyingRepaired) { - int iRepairSec = (int)(tCurrent - m_ParChecker.GetRepairTime()); - pPostInfo->GetNZBInfo()->SetRepairSec(pPostInfo->GetNZBInfo()->GetRepairSec() + iRepairSec); + int repairSec = (int)(current - m_parChecker.GetRepairTime()); + postInfo->GetNZBInfo()->SetRepairSec(postInfo->GetNZBInfo()->GetRepairSec() + repairSec); } } - bool bParCancel = false; - if (!m_ParChecker.GetCancelled()) + bool parCancel = false; + if (!m_parChecker.GetCancelled()) { if ((g_pOptions->GetParTimeLimit() > 0) && - m_ParChecker.GetStage() == ParChecker::ptRepairing && - ((g_pOptions->GetParTimeLimit() > 5 && tCurrent - pPostInfo->GetStageTime() > 5 * 60) || - (g_pOptions->GetParTimeLimit() <= 5 && tCurrent - pPostInfo->GetStageTime() > 1 * 60))) + m_parChecker.GetStage() == ParChecker::ptRepairing && + ((g_pOptions->GetParTimeLimit() > 5 && current - postInfo->GetStageTime() > 5 * 60) || + (g_pOptions->GetParTimeLimit() <= 5 && current - postInfo->GetStageTime() > 1 * 60))) { // first five (or one) minutes elapsed, now can check the estimated time - int iEstimatedRepairTime = (int)((tCurrent - pPostInfo->GetStartTime()) * 1000 / - (pPostInfo->GetStageProgress() > 0 ? pPostInfo->GetStageProgress() : 1)); - if (iEstimatedRepairTime > g_pOptions->GetParTimeLimit() * 60) + int estimatedRepairTime = (int)((current - postInfo->GetStartTime()) * 1000 / + (postInfo->GetStageProgress() > 0 ? postInfo->GetStageProgress() : 1)); + if (estimatedRepairTime > g_pOptions->GetParTimeLimit() * 60) { - debug("Estimated repair time %i seconds", iEstimatedRepairTime); - m_ParChecker.PrintMessage(Message::mkWarning, "Cancelling par-repair for %s, estimated repair time (%i minutes) exceeds allowed repair time", m_ParChecker.GetInfoName(), iEstimatedRepairTime / 60); - bParCancel = true; + debug("Estimated repair time %i seconds", estimatedRepairTime); + m_parChecker.PrintMessage(Message::mkWarning, "Cancelling par-repair for %s, estimated repair time (%i minutes) exceeds allowed repair time", m_parChecker.GetInfoName(), estimatedRepairTime / 60); + parCancel = true; } } } - if (bParCancel) + if (parCancel) { - m_ParChecker.Cancel(); + m_parChecker.Cancel(); } DownloadQueue::Unlock(); - CheckPauseState(pPostInfo); + CheckPauseState(postInfo); } -void ParCoordinator::CheckPauseState(PostInfo* pPostInfo) +void ParCoordinator::CheckPauseState(PostInfo* postInfo) { - if (g_pOptions->GetPausePostProcess() && !pPostInfo->GetNZBInfo()->GetForcePriority()) + if (g_pOptions->GetPausePostProcess() && !postInfo->GetNZBInfo()->GetForcePriority()) { - time_t tStageTime = pPostInfo->GetStageTime(); - time_t tStartTime = pPostInfo->GetStartTime(); - time_t tParTime = m_ParChecker.GetParTime(); - time_t tRepairTime = m_ParChecker.GetRepairTime(); - time_t tWaitTime = time(NULL); + time_t stageTime = postInfo->GetStageTime(); + time_t startTime = postInfo->GetStartTime(); + time_t parTime = m_parChecker.GetParTime(); + time_t repairTime = m_parChecker.GetRepairTime(); + time_t waitTime = time(NULL); // wait until Post-processor is unpaused - while (g_pOptions->GetPausePostProcess() && !pPostInfo->GetNZBInfo()->GetForcePriority() && !m_bStopped) + while (g_pOptions->GetPausePostProcess() && !postInfo->GetNZBInfo()->GetForcePriority() && !m_stopped) { usleep(50 * 1000); // update time stamps - time_t tDelta = time(NULL) - tWaitTime; + time_t delta = time(NULL) - waitTime; - if (tStageTime > 0) + if (stageTime > 0) { - pPostInfo->SetStageTime(tStageTime + tDelta); + postInfo->SetStageTime(stageTime + delta); } - if (tStartTime > 0) + if (startTime > 0) { - pPostInfo->SetStartTime(tStartTime + tDelta); + postInfo->SetStartTime(startTime + delta); } - if (tParTime > 0) + if (parTime > 0) { - m_ParChecker.SetParTime(tParTime + tDelta); + m_parChecker.SetParTime(parTime + delta); } - if (tRepairTime > 0) + if (repairTime > 0) { - m_ParChecker.SetRepairTime(tRepairTime + tDelta); + m_parChecker.SetRepairTime(repairTime + delta); } } } @@ -734,21 +734,21 @@ void ParCoordinator::CheckPauseState(PostInfo* pPostInfo) void ParCoordinator::ParRenameCompleted() { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - PostInfo* pPostInfo = m_ParRenamer.GetPostInfo(); - pPostInfo->GetNZBInfo()->SetRenameStatus(m_ParRenamer.GetStatus() == ParRenamer::psSuccess ? NZBInfo::rsSuccess : NZBInfo::rsFailure); + PostInfo* postInfo = m_parRenamer.GetPostInfo(); + postInfo->GetNZBInfo()->SetRenameStatus(m_parRenamer.GetStatus() == ParRenamer::psSuccess ? NZBInfo::rsSuccess : NZBInfo::rsFailure); - if (m_ParRenamer.HasMissedFiles() && pPostInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped) + if (m_parRenamer.HasMissedFiles() && postInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped) { - m_ParRenamer.PrintMessage(Message::mkInfo, "Requesting par-check/repair for %s to restore missing files ", m_ParRenamer.GetInfoName()); - pPostInfo->SetRequestParCheck(true); + m_parRenamer.PrintMessage(Message::mkInfo, "Requesting par-check/repair for %s to restore missing files ", m_parRenamer.GetInfoName()); + postInfo->SetRequestParCheck(true); } - pPostInfo->SetWorking(false); - pPostInfo->SetStage(PostInfo::ptQueued); + postInfo->SetWorking(false); + postInfo->SetStage(PostInfo::ptQueued); - pDownloadQueue->Save(); + downloadQueue->Save(); DownloadQueue::Unlock(); } @@ -757,20 +757,20 @@ void ParCoordinator::UpdateParRenameProgress() { DownloadQueue::Lock(); - PostInfo* pPostInfo = m_ParRenamer.GetPostInfo(); - pPostInfo->SetProgressLabel(m_ParRenamer.GetProgressLabel()); - pPostInfo->SetStageProgress(m_ParRenamer.GetStageProgress()); - time_t tCurrent = time(NULL); + PostInfo* postInfo = m_parRenamer.GetPostInfo(); + postInfo->SetProgressLabel(m_parRenamer.GetProgressLabel()); + postInfo->SetStageProgress(m_parRenamer.GetStageProgress()); + time_t current = time(NULL); - if (pPostInfo->GetStage() != PostInfo::ptRenaming) + if (postInfo->GetStage() != PostInfo::ptRenaming) { - pPostInfo->SetStage(PostInfo::ptRenaming); - pPostInfo->SetStageTime(tCurrent); + postInfo->SetStage(PostInfo::ptRenaming); + postInfo->SetStageTime(current); } DownloadQueue::Unlock(); - CheckPauseState(pPostInfo); + CheckPauseState(postInfo); } #endif diff --git a/daemon/postprocess/ParCoordinator.h b/daemon/postprocess/ParCoordinator.h index 7cad5af4..e2a8e54a 100644 --- a/daemon/postprocess/ParCoordinator.h +++ b/daemon/postprocess/ParCoordinator.h @@ -44,30 +44,30 @@ private: class PostParChecker: public ParChecker { private: - ParCoordinator* m_pOwner; - PostInfo* m_pPostInfo; - time_t m_tParTime; - time_t m_tRepairTime; - int m_iDownloadSec; + ParCoordinator* m_owner; + PostInfo* m_postInfo; + time_t m_parTime; + time_t m_repairTime; + int m_downloadSec; protected: - virtual bool RequestMorePars(int iBlockNeeded, int* pBlockFound); + virtual bool RequestMorePars(int blockNeeded, int* blockFound); virtual void UpdateProgress(); - virtual void Completed() { m_pOwner->ParCheckCompleted(); } - virtual void PrintMessage(Message::EKind eKind, const char* szFormat, ...); - virtual void RegisterParredFile(const char* szFilename); - virtual bool IsParredFile(const char* szFilename); - virtual EFileStatus FindFileCrc(const char* szFilename, unsigned long* lCrc, SegmentList* pSegments); - virtual void RequestDupeSources(DupeSourceList* pDupeSourceList); - virtual void StatDupeSources(DupeSourceList* pDupeSourceList); + virtual void Completed() { m_owner->ParCheckCompleted(); } + virtual void PrintMessage(Message::EKind kind, const char* format, ...); + virtual void RegisterParredFile(const char* filename); + virtual bool IsParredFile(const char* filename); + virtual EFileStatus FindFileCrc(const char* filename, unsigned long* crc, SegmentList* segments); + virtual void RequestDupeSources(DupeSourceList* dupeSourceList); + virtual void StatDupeSources(DupeSourceList* dupeSourceList); public: - PostInfo* GetPostInfo() { return m_pPostInfo; } - void SetPostInfo(PostInfo* pPostInfo) { m_pPostInfo = pPostInfo; } - time_t GetParTime() { return m_tParTime; } - void SetParTime(time_t tParTime) { m_tParTime = tParTime; } - time_t GetRepairTime() { return m_tRepairTime; } - void SetRepairTime(time_t tRepairTime) { m_tRepairTime = tRepairTime; } - int GetDownloadSec() { return m_iDownloadSec; } - void SetDownloadSec(int iDownloadSec) { m_iDownloadSec = iDownloadSec; } + PostInfo* GetPostInfo() { return m_postInfo; } + void SetPostInfo(PostInfo* postInfo) { m_postInfo = postInfo; } + time_t GetParTime() { return m_parTime; } + void SetParTime(time_t parTime) { m_parTime = parTime; } + time_t GetRepairTime() { return m_repairTime; } + void SetRepairTime(time_t repairTime) { m_repairTime = repairTime; } + int GetDownloadSec() { return m_downloadSec; } + void SetDownloadSec(int downloadSec) { m_downloadSec = downloadSec; } friend class ParCoordinator; }; @@ -75,17 +75,17 @@ private: class PostParRenamer: public ParRenamer { private: - ParCoordinator* m_pOwner; - PostInfo* m_pPostInfo; + ParCoordinator* m_owner; + PostInfo* m_postInfo; protected: virtual void UpdateProgress(); - virtual void Completed() { m_pOwner->ParRenameCompleted(); } - virtual void PrintMessage(Message::EKind eKind, const char* szFormat, ...); - virtual void RegisterParredFile(const char* szFilename); - virtual void RegisterRenamedFile(const char* szOldFilename, const char* szNewFileName); + virtual void Completed() { m_owner->ParRenameCompleted(); } + virtual void PrintMessage(Message::EKind kind, const char* format, ...); + virtual void RegisterParredFile(const char* filename); + virtual void RegisterRenamedFile(const char* oldFilename, const char* newFileName); public: - PostInfo* GetPostInfo() { return m_pPostInfo; } - void SetPostInfo(PostInfo* pPostInfo) { m_pPostInfo = pPostInfo; } + PostInfo* GetPostInfo() { return m_postInfo; } + void SetPostInfo(PostInfo* postInfo) { m_postInfo = postInfo; } friend class ParCoordinator; }; @@ -93,20 +93,20 @@ private: class PostDupeMatcher: public DupeMatcher { private: - PostInfo* m_pPostInfo; + PostInfo* m_postInfo; protected: - virtual void PrintMessage(Message::EKind eKind, const char* szFormat, ...); + virtual void PrintMessage(Message::EKind kind, const char* format, ...); public: - PostDupeMatcher(PostInfo* pPostInfo): - DupeMatcher(pPostInfo->GetNZBInfo()->GetDestDir(), - pPostInfo->GetNZBInfo()->GetSize() - pPostInfo->GetNZBInfo()->GetParSize()), - m_pPostInfo(pPostInfo) {} + PostDupeMatcher(PostInfo* postInfo): + DupeMatcher(postInfo->GetNZBInfo()->GetDestDir(), + postInfo->GetNZBInfo()->GetSize() - postInfo->GetNZBInfo()->GetParSize()), + m_postInfo(postInfo) {} }; struct BlockInfo { - FileInfo* m_pFileInfo; - int m_iBlockCount; + FileInfo* m_fileInfo; + int m_blockCount; }; typedef std::list Blocks; @@ -118,31 +118,31 @@ private: }; private: - PostParChecker m_ParChecker; - bool m_bStopped; - PostParRenamer m_ParRenamer; - EJobKind m_eCurrentJob; + PostParChecker m_parChecker; + bool m_stopped; + PostParRenamer m_parRenamer; + EJobKind m_currentJob; protected: void UpdateParCheckProgress(); void UpdateParRenameProgress(); void ParCheckCompleted(); void ParRenameCompleted(); - void CheckPauseState(PostInfo* pPostInfo); - bool RequestMorePars(NZBInfo* pNZBInfo, const char* szParFilename, int iBlockNeeded, int* pBlockFound); + void CheckPauseState(PostInfo* postInfo); + bool RequestMorePars(NZBInfo* nzbInfo, const char* parFilename, int blockNeeded, int* blockFound); #endif public: ParCoordinator(); virtual ~ParCoordinator(); - void PausePars(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); + void PausePars(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); #ifndef DISABLE_PARCHECK - bool AddPar(FileInfo* pFileInfo, bool bDeleted); - void FindPars(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szParFilename, - Blocks* pBlocks, bool bStrictParName, bool bExactParName, int* pBlockFound); - void StartParCheckJob(PostInfo* pPostInfo); - void StartParRenameJob(PostInfo* pPostInfo); + bool AddPar(FileInfo* fileInfo, bool deleted); + void FindPars(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* parFilename, + Blocks* blocks, bool strictParName, bool exactParName, int* blockFound); + void StartParCheckJob(PostInfo* postInfo); + void StartParRenameJob(PostInfo* postInfo); void Stop(); bool Cancel(); #endif diff --git a/daemon/postprocess/ParParser.cpp b/daemon/postprocess/ParParser.cpp index e6e71676..dcbf0e75 100644 --- a/daemon/postprocess/ParParser.cpp +++ b/daemon/postprocess/ParParser.cpp @@ -46,27 +46,27 @@ #include "Util.h" #include "ParParser.h" -bool ParParser::FindMainPars(const char* szPath, ParFileList* pFileList) +bool ParParser::FindMainPars(const char* path, ParFileList* fileList) { - if (pFileList) + if (fileList) { - pFileList->clear(); + fileList->clear(); } - DirBrowser dir(szPath); + DirBrowser dir(path); while (const char* filename = dir.Next()) { - int iBaseLen = 0; - if (ParseParFilename(filename, &iBaseLen, NULL)) + int baseLen = 0; + if (ParseParFilename(filename, &baseLen, NULL)) { - if (!pFileList) + if (!fileList) { return true; } // check if the base file already added to list bool exists = false; - for (ParFileList::iterator it = pFileList->begin(); it != pFileList->end(); it++) + for (ParFileList::iterator it = fileList->begin(); it != fileList->end(); it++) { const char* filename2 = *it; exists = SameParCollection(filename, filename2); @@ -77,54 +77,54 @@ bool ParParser::FindMainPars(const char* szPath, ParFileList* pFileList) } if (!exists) { - pFileList->push_back(strdup(filename)); + fileList->push_back(strdup(filename)); } } } - return pFileList && !pFileList->empty(); + return fileList && !fileList->empty(); } -bool ParParser::SameParCollection(const char* szFilename1, const char* szFilename2) +bool ParParser::SameParCollection(const char* filename1, const char* filename2) { - int iBaseLen1 = 0, iBaseLen2 = 0; - return ParseParFilename(szFilename1, &iBaseLen1, NULL) && - ParseParFilename(szFilename2, &iBaseLen2, NULL) && - iBaseLen1 == iBaseLen2 && - !strncasecmp(szFilename1, szFilename2, iBaseLen1); + int baseLen1 = 0, baseLen2 = 0; + return ParseParFilename(filename1, &baseLen1, NULL) && + ParseParFilename(filename2, &baseLen2, NULL) && + baseLen1 == baseLen2 && + !strncasecmp(filename1, filename2, baseLen1); } -bool ParParser::ParseParFilename(const char* szParFilename, int* iBaseNameLen, int* iBlocks) +bool ParParser::ParseParFilename(const char* parFilename, int* baseNameLen, int* blocks) { - char szFilename[1024]; - strncpy(szFilename, szParFilename, 1024); - szFilename[1024-1] = '\0'; - for (char* p = szFilename; *p; p++) *p = tolower(*p); // convert string to lowercase + char filename[1024]; + strncpy(filename, parFilename, 1024); + filename[1024-1] = '\0'; + for (char* p = filename; *p; p++) *p = tolower(*p); // convert string to lowercase - int iLen = strlen(szFilename); - if (iLen < 6) + int len = strlen(filename); + if (len < 6) { return false; } // find last occurence of ".par2" and trim filename after it - char* szEnd = szFilename; - while (char* p = strstr(szEnd, ".par2")) szEnd = p + 5; - *szEnd = '\0'; + char* end = filename; + while (char* p = strstr(end, ".par2")) end = p + 5; + *end = '\0'; - iLen = strlen(szFilename); - if (iLen < 6) + len = strlen(filename); + if (len < 6) { return false; } - if (strcasecmp(szFilename + iLen - 5, ".par2")) + if (strcasecmp(filename + len - 5, ".par2")) { return false; } - *(szFilename + iLen - 5) = '\0'; + *(filename + len - 5) = '\0'; int blockcnt = 0; - char* p = strrchr(szFilename, '.'); + char* p = strrchr(filename, '.'); if (p && !strncasecmp(p, ".vol", 4)) { char* b = strchr(p, '+'); @@ -139,13 +139,13 @@ bool ParParser::ParseParFilename(const char* szParFilename, int* iBaseNameLen, i } } - if (iBaseNameLen) + if (baseNameLen) { - *iBaseNameLen = strlen(szFilename); + *baseNameLen = strlen(filename); } - if (iBlocks) + if (blocks) { - *iBlocks = blockcnt; + *blocks = blockcnt; } return true; diff --git a/daemon/postprocess/ParParser.h b/daemon/postprocess/ParParser.h index df0c3ce4..4ecaff10 100644 --- a/daemon/postprocess/ParParser.h +++ b/daemon/postprocess/ParParser.h @@ -33,9 +33,9 @@ class ParParser public: typedef std::deque ParFileList; - static bool FindMainPars(const char* szPath, ParFileList* pFileList); - static bool ParseParFilename(const char* szParFilename, int* iBaseNameLen, int* iBlocks); - static bool SameParCollection(const char* szFilename1, const char* szFilename2); + static bool FindMainPars(const char* path, ParFileList* fileList); + static bool ParseParFilename(const char* parFilename, int* baseNameLen, int* blocks); + static bool SameParCollection(const char* filename1, const char* filename2); }; #endif diff --git a/daemon/postprocess/ParRenamer.cpp b/daemon/postprocess/ParRenamer.cpp index c9533920..beb98cd9 100644 --- a/daemon/postprocess/ParRenamer.cpp +++ b/daemon/postprocess/ParRenamer.cpp @@ -58,40 +58,40 @@ public: friend class ParRenamer; }; -ParRenamer::FileHash::FileHash(const char* szFilename, const char* szHash) +ParRenamer::FileHash::FileHash(const char* filename, const char* hash) { - m_szFilename = strdup(szFilename); - m_szHash = strdup(szHash); - m_bFileExists = false; + m_filename = strdup(filename); + m_hash = strdup(hash); + m_fileExists = false; } ParRenamer::FileHash::~FileHash() { - free(m_szFilename); - free(m_szHash); + free(m_filename); + free(m_hash); } ParRenamer::ParRenamer() { debug("Creating ParRenamer"); - m_eStatus = psFailed; - m_szDestDir = NULL; - m_szInfoName = NULL; - m_szProgressLabel = (char*)malloc(1024); - m_iStageProgress = 0; - m_bCancelled = false; - m_bHasMissedFiles = false; - m_bDetectMissing = false; + m_status = psFailed; + m_destDir = NULL; + m_infoName = NULL; + m_progressLabel = (char*)malloc(1024); + m_stageProgress = 0; + m_cancelled = false; + m_hasMissedFiles = false; + m_detectMissing = false; } ParRenamer::~ParRenamer() { debug("Destroying ParRenamer"); - free(m_szDestDir); - free(m_szInfoName); - free(m_szProgressLabel); + free(m_destDir); + free(m_infoName); + free(m_progressLabel); Cleanup(); } @@ -100,159 +100,159 @@ void ParRenamer::Cleanup() { ClearHashList(); - for (DirList::iterator it = m_DirList.begin(); it != m_DirList.end(); it++) + for (DirList::iterator it = m_dirList.begin(); it != m_dirList.end(); it++) { free(*it); } - m_DirList.clear(); + m_dirList.clear(); } void ParRenamer::ClearHashList() { - for (FileHashList::iterator it = m_FileHashList.begin(); it != m_FileHashList.end(); it++) + for (FileHashList::iterator it = m_fileHashList.begin(); it != m_fileHashList.end(); it++) { delete *it; } - m_FileHashList.clear(); + m_fileHashList.clear(); } -void ParRenamer::SetDestDir(const char * szDestDir) +void ParRenamer::SetDestDir(const char * destDir) { - free(m_szDestDir); - m_szDestDir = strdup(szDestDir); + free(m_destDir); + m_destDir = strdup(destDir); } -void ParRenamer::SetInfoName(const char * szInfoName) +void ParRenamer::SetInfoName(const char * infoName) { - free(m_szInfoName); - m_szInfoName = strdup(szInfoName); + free(m_infoName); + m_infoName = strdup(infoName); } void ParRenamer::Cancel() { - m_bCancelled = true; + m_cancelled = true; } void ParRenamer::Run() { Cleanup(); - m_bCancelled = false; - m_iFileCount = 0; - m_iCurFile = 0; - m_iRenamedCount = 0; - m_bHasMissedFiles = false; - m_eStatus = psFailed; + m_cancelled = false; + m_fileCount = 0; + m_curFile = 0; + m_renamedCount = 0; + m_hasMissedFiles = false; + m_status = psFailed; - snprintf(m_szProgressLabel, 1024, "Checking renamed files for %s", m_szInfoName); - m_szProgressLabel[1024-1] = '\0'; - m_iStageProgress = 0; + snprintf(m_progressLabel, 1024, "Checking renamed files for %s", m_infoName); + m_progressLabel[1024-1] = '\0'; + m_stageProgress = 0; UpdateProgress(); - BuildDirList(m_szDestDir); + BuildDirList(m_destDir); - for (DirList::iterator it = m_DirList.begin(); it != m_DirList.end(); it++) + for (DirList::iterator it = m_dirList.begin(); it != m_dirList.end(); it++) { - char* szDestDir = *it; - debug("Checking %s", szDestDir); + char* destDir = *it; + debug("Checking %s", destDir); ClearHashList(); - LoadParFiles(szDestDir); + LoadParFiles(destDir); - if (m_FileHashList.empty()) + if (m_fileHashList.empty()) { - int iSavedCurFile = m_iCurFile; - CheckFiles(szDestDir, true); - m_iCurFile = iSavedCurFile; // restore progress indicator - LoadParFiles(szDestDir); + int savedCurFile = m_curFile; + CheckFiles(destDir, true); + m_curFile = savedCurFile; // restore progress indicator + LoadParFiles(destDir); } - CheckFiles(szDestDir, false); + CheckFiles(destDir, false); - if (m_bDetectMissing) + if (m_detectMissing) { CheckMissing(); } } - if (m_bCancelled) + if (m_cancelled) { - PrintMessage(Message::mkWarning, "Renaming cancelled for %s", m_szInfoName); + PrintMessage(Message::mkWarning, "Renaming cancelled for %s", m_infoName); } - else if (m_iRenamedCount > 0) + else if (m_renamedCount > 0) { - PrintMessage(Message::mkInfo, "Successfully renamed %i file(s) for %s", m_iRenamedCount, m_szInfoName); - m_eStatus = psSuccess; + PrintMessage(Message::mkInfo, "Successfully renamed %i file(s) for %s", m_renamedCount, m_infoName); + m_status = psSuccess; } else { - PrintMessage(Message::mkInfo, "No renamed files found for %s", m_szInfoName); + PrintMessage(Message::mkInfo, "No renamed files found for %s", m_infoName); } Cleanup(); Completed(); } -void ParRenamer::BuildDirList(const char* szDestDir) +void ParRenamer::BuildDirList(const char* destDir) { - m_DirList.push_back(strdup(szDestDir)); + m_dirList.push_back(strdup(destDir)); - char* szFullFilename = (char*)malloc(1024); - DirBrowser* pDirBrowser = new DirBrowser(szDestDir); + char* fullFilename = (char*)malloc(1024); + DirBrowser* dirBrowser = new DirBrowser(destDir); - while (const char* filename = pDirBrowser->Next()) + while (const char* filename = dirBrowser->Next()) { - if (strcmp(filename, ".") && strcmp(filename, "..") && !m_bCancelled) + if (strcmp(filename, ".") && strcmp(filename, "..") && !m_cancelled) { - snprintf(szFullFilename, 1024, "%s%c%s", szDestDir, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + snprintf(fullFilename, 1024, "%s%c%s", destDir, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - if (Util::DirectoryExists(szFullFilename)) + if (Util::DirectoryExists(fullFilename)) { - BuildDirList(szFullFilename); + BuildDirList(fullFilename); } else { - m_iFileCount++; + m_fileCount++; } } } - free(szFullFilename); - delete pDirBrowser; + free(fullFilename); + delete dirBrowser; } -void ParRenamer::LoadParFiles(const char* szDestDir) +void ParRenamer::LoadParFiles(const char* destDir) { ParParser::ParFileList parFileList; - ParParser::FindMainPars(szDestDir, &parFileList); + ParParser::FindMainPars(destDir, &parFileList); for (ParParser::ParFileList::iterator it = parFileList.begin(); it != parFileList.end(); it++) { - char* szParFilename = *it; + char* parFilename = *it; - char szFullParFilename[1024]; - snprintf(szFullParFilename, 1024, "%s%c%s", szDestDir, PATH_SEPARATOR, szParFilename); - szFullParFilename[1024-1] = '\0'; + char fullParFilename[1024]; + snprintf(fullParFilename, 1024, "%s%c%s", destDir, PATH_SEPARATOR, parFilename); + fullParFilename[1024-1] = '\0'; - LoadParFile(szFullParFilename); + LoadParFile(fullParFilename); free(*it); } } -void ParRenamer::LoadParFile(const char* szParFilename) +void ParRenamer::LoadParFile(const char* parFilename) { - ParRenamerRepairer* pRepairer = new ParRenamerRepairer(); + ParRenamerRepairer* repairer = new ParRenamerRepairer(); - if (!pRepairer->LoadPacketsFromFile(szParFilename)) + if (!repairer->LoadPacketsFromFile(parFilename)) { - PrintMessage(Message::mkWarning, "Could not load par2-file %s", szParFilename); - delete pRepairer; + PrintMessage(Message::mkWarning, "Could not load par2-file %s", parFilename); + delete repairer; return; } - for (map::iterator it = pRepairer->sourcefilemap.begin(); it != pRepairer->sourcefilemap.end(); it++) + for (map::iterator it = repairer->sourcefilemap.begin(); it != repairer->sourcefilemap.end(); it++) { - if (m_bCancelled) + if (m_cancelled) { break; } @@ -260,43 +260,43 @@ void ParRenamer::LoadParFile(const char* szParFilename) Par2RepairerSourceFile* sourceFile = (*it).second; if (!sourceFile || !sourceFile->GetDescriptionPacket()) { - PrintMessage(Message::mkWarning, "Damaged par2-file detected: %s", szParFilename); + PrintMessage(Message::mkWarning, "Damaged par2-file detected: %s", parFilename); continue; } - m_FileHashList.push_back(new FileHash(sourceFile->GetDescriptionPacket()->FileName().c_str(), + m_fileHashList.push_back(new FileHash(sourceFile->GetDescriptionPacket()->FileName().c_str(), sourceFile->GetDescriptionPacket()->Hash16k().print().c_str())); RegisterParredFile(sourceFile->GetDescriptionPacket()->FileName().c_str()); } - delete pRepairer; + delete repairer; } -void ParRenamer::CheckFiles(const char* szDestDir, bool bRenamePars) +void ParRenamer::CheckFiles(const char* destDir, bool renamePars) { - DirBrowser dir(szDestDir); + DirBrowser dir(destDir); while (const char* filename = dir.Next()) { - if (strcmp(filename, ".") && strcmp(filename, "..") && !m_bCancelled) + if (strcmp(filename, ".") && strcmp(filename, "..") && !m_cancelled) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", szDestDir, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", destDir, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - if (!Util::DirectoryExists(szFullFilename)) + if (!Util::DirectoryExists(fullFilename)) { - snprintf(m_szProgressLabel, 1024, "Checking file %s", filename); - m_szProgressLabel[1024-1] = '\0'; - m_iStageProgress = m_iCurFile * 1000 / m_iFileCount; + snprintf(m_progressLabel, 1024, "Checking file %s", filename); + m_progressLabel[1024-1] = '\0'; + m_stageProgress = m_curFile * 1000 / m_fileCount; UpdateProgress(); - m_iCurFile++; + m_curFile++; - if (bRenamePars) + if (renamePars) { - CheckParFile(szDestDir, szFullFilename); + CheckParFile(destDir, fullFilename); } else { - CheckRegularFile(szDestDir, szFullFilename); + CheckRegularFile(destDir, fullFilename); } } } @@ -305,96 +305,96 @@ void ParRenamer::CheckFiles(const char* szDestDir, bool bRenamePars) void ParRenamer::CheckMissing() { - for (FileHashList::iterator it = m_FileHashList.begin(); it != m_FileHashList.end(); it++) + for (FileHashList::iterator it = m_fileHashList.begin(); it != m_fileHashList.end(); it++) { - FileHash* pFileHash = *it; - if (!pFileHash->GetFileExists()) + FileHash* fileHash = *it; + if (!fileHash->GetFileExists()) { - if (Util::MatchFileExt(pFileHash->GetFilename(), g_pOptions->GetParIgnoreExt(), ",;") || - Util::MatchFileExt(pFileHash->GetFilename(), g_pOptions->GetExtCleanupDisk(), ",;")) + if (Util::MatchFileExt(fileHash->GetFilename(), g_pOptions->GetParIgnoreExt(), ",;") || + Util::MatchFileExt(fileHash->GetFilename(), g_pOptions->GetExtCleanupDisk(), ",;")) { - PrintMessage(Message::mkInfo, "File %s is missing, ignoring", pFileHash->GetFilename()); + PrintMessage(Message::mkInfo, "File %s is missing, ignoring", fileHash->GetFilename()); } else { - PrintMessage(Message::mkInfo, "File %s is missing", pFileHash->GetFilename()); - m_bHasMissedFiles = true; + PrintMessage(Message::mkInfo, "File %s is missing", fileHash->GetFilename()); + m_hasMissedFiles = true; } } } } -bool ParRenamer::IsSplittedFragment(const char* szFilename, const char* szCorrectName) +bool ParRenamer::IsSplittedFragment(const char* filename, const char* correctName) { - bool bSplittedFragement = false; - const char* szDiskBasename = Util::BaseFileName(szFilename); - const char* szExtension = strrchr(szDiskBasename, '.'); - int iBaseLen = strlen(szCorrectName); - if (szExtension && !strncasecmp(szDiskBasename, szCorrectName, iBaseLen)) + bool splittedFragement = false; + const char* diskBasename = Util::BaseFileName(filename); + const char* extension = strrchr(diskBasename, '.'); + int baseLen = strlen(correctName); + if (extension && !strncasecmp(diskBasename, correctName, baseLen)) { - const char* p = szDiskBasename + iBaseLen; + const char* p = diskBasename + baseLen; if (*p == '.') { for (p++; *p && strchr("0123456789", *p); p++) ; - bSplittedFragement = !*p; - bSplittedFragement = bSplittedFragement && atoi(szDiskBasename + iBaseLen + 1) <= 1; // .000 or .001 + splittedFragement = !*p; + splittedFragement = splittedFragement && atoi(diskBasename + baseLen + 1) <= 1; // .000 or .001 } } - return bSplittedFragement; + return splittedFragement; } -void ParRenamer::CheckRegularFile(const char* szDestDir, const char* szFilename) +void ParRenamer::CheckRegularFile(const char* destDir, const char* filename) { - debug("Computing hash for %s", szFilename); + debug("Computing hash for %s", filename); - const int iBlockSize = 16*1024; + const int blockSize = 16*1024; - FILE* pFile = fopen(szFilename, FOPEN_RB); - if (!pFile) + FILE* file = fopen(filename, FOPEN_RB); + if (!file) { - PrintMessage(Message::mkError, "Could not open file %s", szFilename); + PrintMessage(Message::mkError, "Could not open file %s", filename); return; } // load first 16K of the file into buffer - void* pBuffer = malloc(iBlockSize); + void* buffer = malloc(blockSize); - int iReadBytes = fread(pBuffer, 1, iBlockSize, pFile); - int iError = ferror(pFile); - if (iReadBytes != iBlockSize && iError) + int readBytes = fread(buffer, 1, blockSize, file); + int error = ferror(file); + if (readBytes != blockSize && error) { - PrintMessage(Message::mkError, "Could not read file %s", szFilename); + PrintMessage(Message::mkError, "Could not read file %s", filename); return; } - fclose(pFile); + fclose(file); MD5Hash hash16k; MD5Context context; - context.Update(pBuffer, iReadBytes); + context.Update(buffer, readBytes); context.Final(hash16k); - free(pBuffer); + free(buffer); - debug("file: %s; hash16k: %s", Util::BaseFileName(szFilename), hash16k.print().c_str()); + debug("file: %s; hash16k: %s", Util::BaseFileName(filename), hash16k.print().c_str()); - for (FileHashList::iterator it = m_FileHashList.begin(); it != m_FileHashList.end(); it++) + for (FileHashList::iterator it = m_fileHashList.begin(); it != m_fileHashList.end(); it++) { - FileHash* pFileHash = *it; - if (!strcmp(pFileHash->GetHash(), hash16k.print().c_str())) + FileHash* fileHash = *it; + if (!strcmp(fileHash->GetHash(), hash16k.print().c_str())) { - debug("Found correct filename: %s", pFileHash->GetFilename()); - pFileHash->SetFileExists(true); + debug("Found correct filename: %s", fileHash->GetFilename()); + fileHash->SetFileExists(true); - char szDstFilename[1024]; - snprintf(szDstFilename, 1024, "%s%c%s", szDestDir, PATH_SEPARATOR, pFileHash->GetFilename()); - szDstFilename[1024-1] = '\0'; + char dstFilename[1024]; + snprintf(dstFilename, 1024, "%s%c%s", destDir, PATH_SEPARATOR, fileHash->GetFilename()); + dstFilename[1024-1] = '\0'; - if (!Util::FileExists(szDstFilename) && !IsSplittedFragment(szFilename, pFileHash->GetFilename())) + if (!Util::FileExists(dstFilename) && !IsSplittedFragment(filename, fileHash->GetFilename())) { - RenameFile(szFilename, szDstFilename); + RenameFile(filename, dstFilename); } break; @@ -406,82 +406,82 @@ void ParRenamer::CheckRegularFile(const char* szDestDir, const char* szFilename) * For files not having par2-extensions: checks if the file is a par2-file and renames * it according to its set-id. */ -void ParRenamer::CheckParFile(const char* szDestDir, const char* szFilename) +void ParRenamer::CheckParFile(const char* destDir, const char* filename) { - debug("Checking par2-header for %s", szFilename); + debug("Checking par2-header for %s", filename); - const char* szBasename = Util::BaseFileName(szFilename); - const char* szExtension = strrchr(szBasename, '.'); - if (szExtension && !strcasecmp(szExtension, ".par2")) + const char* basename = Util::BaseFileName(filename); + const char* extension = strrchr(basename, '.'); + if (extension && !strcasecmp(extension, ".par2")) { // do not process files already having par2-extension return; } - FILE* pFile = fopen(szFilename, FOPEN_RB); - if (!pFile) + FILE* file = fopen(filename, FOPEN_RB); + if (!file) { - PrintMessage(Message::mkError, "Could not open file %s", szFilename); + PrintMessage(Message::mkError, "Could not open file %s", filename); return; } // load par2-header PACKET_HEADER header; - int iReadBytes = fread(&header, 1, sizeof(header), pFile); - int iError = ferror(pFile); - if (iReadBytes != sizeof(header) && iError) + int readBytes = fread(&header, 1, sizeof(header), file); + int error = ferror(file); + if (readBytes != sizeof(header) && error) { - PrintMessage(Message::mkError, "Could not read file %s", szFilename); + PrintMessage(Message::mkError, "Could not read file %s", filename); return; } - fclose(pFile); + fclose(file); // Check the packet header if (packet_magic != header.magic || // not par2-file sizeof(PACKET_HEADER) > header.length || // packet length is too small 0 != (header.length & 3) || // packet length is not a multiple of 4 - Util::FileSize(szFilename) < (int)header.length) // packet would extend beyond the end of the file + Util::FileSize(filename) < (int)header.length) // packet would extend beyond the end of the file { // not par2-file or damaged header, ignoring the file return; } - char szSetId[33]; - strncpy(szSetId, header.setid.print().c_str(), sizeof(szSetId)); - szSetId[33-1] = '\0'; - for (char* p = szSetId; *p; p++) *p = tolower(*p); // convert string to lowercase + char setId[33]; + strncpy(setId, header.setid.print().c_str(), sizeof(setId)); + setId[33-1] = '\0'; + for (char* p = setId; *p; p++) *p = tolower(*p); // convert string to lowercase - debug("Renaming: %s; setid: %s", Util::BaseFileName(szFilename), szSetId); + debug("Renaming: %s; setid: %s", Util::BaseFileName(filename), setId); - char szDestFileName[1024]; - int iNum = 1; - while (iNum == 1 || Util::FileExists(szDestFileName)) + char destFileName[1024]; + int num = 1; + while (num == 1 || Util::FileExists(destFileName)) { - snprintf(szDestFileName, 1024, "%s%c%s.vol%03i+01.PAR2", szDestDir, PATH_SEPARATOR, szSetId, iNum); - szDestFileName[1024-1] = '\0'; - iNum++; + snprintf(destFileName, 1024, "%s%c%s.vol%03i+01.PAR2", destDir, PATH_SEPARATOR, setId, num); + destFileName[1024-1] = '\0'; + num++; } - RenameFile(szFilename, szDestFileName); + RenameFile(filename, destFileName); } -void ParRenamer::RenameFile(const char* szSrcFilename, const char* szDestFileName) +void ParRenamer::RenameFile(const char* srcFilename, const char* destFileName) { - PrintMessage(Message::mkInfo, "Renaming %s to %s", Util::BaseFileName(szSrcFilename), Util::BaseFileName(szDestFileName)); - if (!Util::MoveFile(szSrcFilename, szDestFileName)) + PrintMessage(Message::mkInfo, "Renaming %s to %s", Util::BaseFileName(srcFilename), Util::BaseFileName(destFileName)); + if (!Util::MoveFile(srcFilename, destFileName)) { - char szErrBuf[256]; - PrintMessage(Message::mkError, "Could not rename %s to %s: %s", szSrcFilename, szDestFileName, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + char errBuf[256]; + PrintMessage(Message::mkError, "Could not rename %s to %s: %s", srcFilename, destFileName, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); return; } - m_iRenamedCount++; + m_renamedCount++; // notify about new file name - RegisterRenamedFile(Util::BaseFileName(szSrcFilename), Util::BaseFileName(szDestFileName)); + RegisterRenamedFile(Util::BaseFileName(srcFilename), Util::BaseFileName(destFileName)); } #endif diff --git a/daemon/postprocess/ParRenamer.h b/daemon/postprocess/ParRenamer.h index 8a13110b..4ec6a9c9 100644 --- a/daemon/postprocess/ParRenamer.h +++ b/daemon/postprocess/ParRenamer.h @@ -45,72 +45,72 @@ public: class FileHash { private: - char* m_szFilename; - char* m_szHash; - bool m_bFileExists; + char* m_filename; + char* m_hash; + bool m_fileExists; public: - FileHash(const char* szFilename, const char* szHash); + FileHash(const char* filename, const char* hash); ~FileHash(); - const char* GetFilename() { return m_szFilename; } - const char* GetHash() { return m_szHash; } - bool GetFileExists() { return m_bFileExists; } - void SetFileExists(bool bFileExists) { m_bFileExists = bFileExists; } + const char* GetFilename() { return m_filename; } + const char* GetHash() { return m_hash; } + bool GetFileExists() { return m_fileExists; } + void SetFileExists(bool fileExists) { m_fileExists = fileExists; } }; typedef std::deque FileHashList; typedef std::deque DirList; private: - char* m_szInfoName; - char* m_szDestDir; - EStatus m_eStatus; - char* m_szProgressLabel; - int m_iStageProgress; - bool m_bCancelled; - DirList m_DirList; - FileHashList m_FileHashList; - int m_iFileCount; - int m_iCurFile; - int m_iRenamedCount; - bool m_bHasMissedFiles; - bool m_bDetectMissing; + char* m_infoName; + char* m_destDir; + EStatus m_status; + char* m_progressLabel; + int m_stageProgress; + bool m_cancelled; + DirList m_dirList; + FileHashList m_fileHashList; + int m_fileCount; + int m_curFile; + int m_renamedCount; + bool m_hasMissedFiles; + bool m_detectMissing; void Cleanup(); void ClearHashList(); - void BuildDirList(const char* szDestDir); - void CheckDir(const char* szDestDir); - void LoadParFiles(const char* szDestDir); - void LoadParFile(const char* szParFilename); - void CheckFiles(const char* szDestDir, bool bRenamePars); - void CheckRegularFile(const char* szDestDir, const char* szFilename); - void CheckParFile(const char* szDestDir, const char* szFilename); - bool IsSplittedFragment(const char* szFilename, const char* szCorrectName); + void BuildDirList(const char* destDir); + void CheckDir(const char* destDir); + void LoadParFiles(const char* destDir); + void LoadParFile(const char* parFilename); + void CheckFiles(const char* destDir, bool renamePars); + void CheckRegularFile(const char* destDir, const char* filename); + void CheckParFile(const char* destDir, const char* filename); + bool IsSplittedFragment(const char* filename, const char* correctName); void CheckMissing(); - void RenameFile(const char* szSrcFilename, const char* szDestFileName); + void RenameFile(const char* srcFilename, const char* destFileName); protected: virtual void UpdateProgress() {} virtual void Completed() {} - virtual void PrintMessage(Message::EKind eKind, const char* szFormat, ...) {} - virtual void RegisterParredFile(const char* szFilename) {} - virtual void RegisterRenamedFile(const char* szOldFilename, const char* szNewFileName) {} - const char* GetProgressLabel() { return m_szProgressLabel; } - int GetStageProgress() { return m_iStageProgress; } + virtual void PrintMessage(Message::EKind kind, const char* format, ...) {} + virtual void RegisterParredFile(const char* filename) {} + virtual void RegisterRenamedFile(const char* oldFilename, const char* newFileName) {} + const char* GetProgressLabel() { return m_progressLabel; } + int GetStageProgress() { return m_stageProgress; } public: ParRenamer(); virtual ~ParRenamer(); virtual void Run(); - void SetDestDir(const char* szDestDir); - const char* GetInfoName() { return m_szInfoName; } - void SetInfoName(const char* szInfoName); - void SetStatus(EStatus eStatus); - EStatus GetStatus() { return m_eStatus; } + void SetDestDir(const char* destDir); + const char* GetInfoName() { return m_infoName; } + void SetInfoName(const char* infoName); + void SetStatus(EStatus status); + EStatus GetStatus() { return m_status; } void Cancel(); - bool GetCancelled() { return m_bCancelled; } - bool HasMissedFiles() { return m_bHasMissedFiles; } - void SetDetectMissing(bool bDetectMissing) { m_bDetectMissing = bDetectMissing; } + bool GetCancelled() { return m_cancelled; } + bool HasMissedFiles() { return m_hasMissedFiles; } + void SetDetectMissing(bool detectMissing) { m_detectMissing = detectMissing; } }; #endif diff --git a/daemon/postprocess/PrePostProcessor.cpp b/daemon/postprocess/PrePostProcessor.cpp index 50ea035a..273e7009 100644 --- a/daemon/postprocess/PrePostProcessor.cpp +++ b/daemon/postprocess/PrePostProcessor.cpp @@ -60,13 +60,13 @@ PrePostProcessor::PrePostProcessor() { debug("Creating PrePostProcessor"); - m_iJobCount = 0; - m_pCurJob = NULL; - m_szPauseReason = NULL; + m_jobCount = 0; + m_curJob = NULL; + m_pauseReason = NULL; - m_DownloadQueueObserver.m_pOwner = this; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - pDownloadQueue->Attach(&m_DownloadQueueObserver); + m_downloadQueueObserver.m_owner = this; + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + downloadQueue->Attach(&m_downloadQueueObserver); DownloadQueue::Unlock(); } @@ -86,8 +86,8 @@ void PrePostProcessor::Run() if (g_pOptions->GetServerMode() && g_pOptions->GetSaveQueue() && g_pOptions->GetReloadQueue()) { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - SanitisePostQueue(pDownloadQueue); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + SanitisePostQueue(downloadQueue); DownloadQueue::Unlock(); } @@ -99,7 +99,7 @@ void PrePostProcessor::Run() CheckPostQueue(); } - Util::SetStandByMode(!m_pCurJob); + Util::SetStandByMode(!m_curJob); usleep(200 * 1000); } @@ -113,18 +113,18 @@ void PrePostProcessor::Stop() DownloadQueue::Lock(); #ifndef DISABLE_PARCHECK - m_ParCoordinator.Stop(); + m_parCoordinator.Stop(); #endif - if (m_pCurJob && m_pCurJob->GetPostInfo() && - (m_pCurJob->GetPostInfo()->GetStage() == PostInfo::ptUnpacking || - m_pCurJob->GetPostInfo()->GetStage() == PostInfo::ptExecutingScript) && - m_pCurJob->GetPostInfo()->GetPostThread()) + if (m_curJob && m_curJob->GetPostInfo() && + (m_curJob->GetPostInfo()->GetStage() == PostInfo::ptUnpacking || + m_curJob->GetPostInfo()->GetStage() == PostInfo::ptExecutingScript) && + m_curJob->GetPostInfo()->GetPostThread()) { - Thread* pPostThread = m_pCurJob->GetPostInfo()->GetPostThread(); - m_pCurJob->GetPostInfo()->SetPostThread(NULL); - pPostThread->SetAutoDestroy(true); - pPostThread->Stop(); + Thread* postThread = m_curJob->GetPostInfo()->GetPostThread(); + m_curJob->GetPostInfo()->SetPostThread(NULL); + postThread->SetAutoDestroy(true); + postThread->Stop(); } DownloadQueue::Unlock(); @@ -137,303 +137,303 @@ void PrePostProcessor::DownloadQueueUpdate(Subject* Caller, void* Aspect) return; } - DownloadQueue::Aspect* pQueueAspect = (DownloadQueue::Aspect*)Aspect; - if (pQueueAspect->eAction == DownloadQueue::eaNzbFound) + DownloadQueue::Aspect* queueAspect = (DownloadQueue::Aspect*)Aspect; + if (queueAspect->action == DownloadQueue::eaNzbFound) { - NZBFound(pQueueAspect->pDownloadQueue, pQueueAspect->pNZBInfo); + NZBFound(queueAspect->downloadQueue, queueAspect->nzbInfo); } - else if (pQueueAspect->eAction == DownloadQueue::eaNzbAdded) + else if (queueAspect->action == DownloadQueue::eaNzbAdded) { - NZBAdded(pQueueAspect->pDownloadQueue, pQueueAspect->pNZBInfo); + NZBAdded(queueAspect->downloadQueue, queueAspect->nzbInfo); } - else if (pQueueAspect->eAction == DownloadQueue::eaNzbDeleted && - pQueueAspect->pNZBInfo->GetDeleting() && - !pQueueAspect->pNZBInfo->GetPostInfo() && - !pQueueAspect->pNZBInfo->GetParCleanup() && - pQueueAspect->pNZBInfo->GetFileList()->empty()) + else if (queueAspect->action == DownloadQueue::eaNzbDeleted && + queueAspect->nzbInfo->GetDeleting() && + !queueAspect->nzbInfo->GetPostInfo() && + !queueAspect->nzbInfo->GetParCleanup() && + queueAspect->nzbInfo->GetFileList()->empty()) { // the deleting of nzbs is usually handled via eaFileDeleted-event, but when deleting nzb without // any files left the eaFileDeleted-event is not fired and we need to process eaNzbDeleted-event instead - pQueueAspect->pNZBInfo->PrintMessage(Message::mkInfo, - "Collection %s deleted from queue", pQueueAspect->pNZBInfo->GetName()); - NZBDeleted(pQueueAspect->pDownloadQueue, pQueueAspect->pNZBInfo); + queueAspect->nzbInfo->PrintMessage(Message::mkInfo, + "Collection %s deleted from queue", queueAspect->nzbInfo->GetName()); + NZBDeleted(queueAspect->downloadQueue, queueAspect->nzbInfo); } - else if ((pQueueAspect->eAction == DownloadQueue::eaFileCompleted || - pQueueAspect->eAction == DownloadQueue::eaFileDeleted)) + else if ((queueAspect->action == DownloadQueue::eaFileCompleted || + queueAspect->action == DownloadQueue::eaFileDeleted)) { - if (pQueueAspect->eAction == DownloadQueue::eaFileCompleted && !pQueueAspect->pNZBInfo->GetPostInfo()) + if (queueAspect->action == DownloadQueue::eaFileCompleted && !queueAspect->nzbInfo->GetPostInfo()) { - g_pQueueScriptCoordinator->EnqueueScript(pQueueAspect->pNZBInfo, QueueScriptCoordinator::qeFileDownloaded); + g_pQueueScriptCoordinator->EnqueueScript(queueAspect->nzbInfo, QueueScriptCoordinator::qeFileDownloaded); } if ( #ifndef DISABLE_PARCHECK - !m_ParCoordinator.AddPar(pQueueAspect->pFileInfo, pQueueAspect->eAction == DownloadQueue::eaFileDeleted) && + !m_parCoordinator.AddPar(queueAspect->fileInfo, queueAspect->action == DownloadQueue::eaFileDeleted) && #endif - IsNZBFileCompleted(pQueueAspect->pNZBInfo, true, false) && - !pQueueAspect->pNZBInfo->GetPostInfo() && - (!pQueueAspect->pFileInfo->GetPaused() || IsNZBFileCompleted(pQueueAspect->pNZBInfo, false, false))) + IsNZBFileCompleted(queueAspect->nzbInfo, true, false) && + !queueAspect->nzbInfo->GetPostInfo() && + (!queueAspect->fileInfo->GetPaused() || IsNZBFileCompleted(queueAspect->nzbInfo, false, false))) { - if ((pQueueAspect->eAction == DownloadQueue::eaFileCompleted || - (pQueueAspect->pFileInfo->GetAutoDeleted() && - IsNZBFileCompleted(pQueueAspect->pNZBInfo, false, true))) && - pQueueAspect->pFileInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsHealth) + if ((queueAspect->action == DownloadQueue::eaFileCompleted || + (queueAspect->fileInfo->GetAutoDeleted() && + IsNZBFileCompleted(queueAspect->nzbInfo, false, true))) && + queueAspect->fileInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsHealth) { - pQueueAspect->pNZBInfo->PrintMessage(Message::mkInfo, - "Collection %s completely downloaded", pQueueAspect->pNZBInfo->GetName()); - g_pQueueScriptCoordinator->EnqueueScript(pQueueAspect->pNZBInfo, QueueScriptCoordinator::qeNzbDownloaded); - NZBDownloaded(pQueueAspect->pDownloadQueue, pQueueAspect->pNZBInfo); + queueAspect->nzbInfo->PrintMessage(Message::mkInfo, + "Collection %s completely downloaded", queueAspect->nzbInfo->GetName()); + g_pQueueScriptCoordinator->EnqueueScript(queueAspect->nzbInfo, QueueScriptCoordinator::qeNzbDownloaded); + NZBDownloaded(queueAspect->downloadQueue, queueAspect->nzbInfo); } - else if ((pQueueAspect->eAction == DownloadQueue::eaFileDeleted || - (pQueueAspect->eAction == DownloadQueue::eaFileCompleted && - pQueueAspect->pFileInfo->GetNZBInfo()->GetDeleteStatus() > NZBInfo::dsNone)) && - !pQueueAspect->pNZBInfo->GetParCleanup() && - IsNZBFileCompleted(pQueueAspect->pNZBInfo, false, true)) + else if ((queueAspect->action == DownloadQueue::eaFileDeleted || + (queueAspect->action == DownloadQueue::eaFileCompleted && + queueAspect->fileInfo->GetNZBInfo()->GetDeleteStatus() > NZBInfo::dsNone)) && + !queueAspect->nzbInfo->GetParCleanup() && + IsNZBFileCompleted(queueAspect->nzbInfo, false, true)) { - pQueueAspect->pNZBInfo->PrintMessage(Message::mkInfo, - "Collection %s deleted from queue", pQueueAspect->pNZBInfo->GetName()); - NZBDeleted(pQueueAspect->pDownloadQueue, pQueueAspect->pNZBInfo); + queueAspect->nzbInfo->PrintMessage(Message::mkInfo, + "Collection %s deleted from queue", queueAspect->nzbInfo->GetName()); + NZBDeleted(queueAspect->downloadQueue, queueAspect->nzbInfo); } } } } -void PrePostProcessor::NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void PrePostProcessor::NZBFound(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { - if (g_pOptions->GetDupeCheck() && pNZBInfo->GetDupeMode() != dmForce) + if (g_pOptions->GetDupeCheck() && nzbInfo->GetDupeMode() != dmForce) { - g_pDupeCoordinator->NZBFound(pDownloadQueue, pNZBInfo); + g_pDupeCoordinator->NZBFound(downloadQueue, nzbInfo); } } -void PrePostProcessor::NZBAdded(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void PrePostProcessor::NZBAdded(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { if (g_pOptions->GetParCheck() != Options::pcForce) { - m_ParCoordinator.PausePars(pDownloadQueue, pNZBInfo); + m_parCoordinator.PausePars(downloadQueue, nzbInfo); } - if (pNZBInfo->GetDeleteStatus() == NZBInfo::dsDupe || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsCopy || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsGood || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsScan) + if (nzbInfo->GetDeleteStatus() == NZBInfo::dsDupe || + nzbInfo->GetDeleteStatus() == NZBInfo::dsCopy || + nzbInfo->GetDeleteStatus() == NZBInfo::dsGood || + nzbInfo->GetDeleteStatus() == NZBInfo::dsScan) { - NZBCompleted(pDownloadQueue, pNZBInfo, false); + NZBCompleted(downloadQueue, nzbInfo, false); } else { - g_pQueueScriptCoordinator->EnqueueScript(pNZBInfo, QueueScriptCoordinator::qeNzbAdded); + g_pQueueScriptCoordinator->EnqueueScript(nzbInfo, QueueScriptCoordinator::qeNzbAdded); } } -void PrePostProcessor::NZBDownloaded(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void PrePostProcessor::NZBDownloaded(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { - if (pNZBInfo->GetDeleteStatus() == NZBInfo::dsHealth || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsBad) + if (nzbInfo->GetDeleteStatus() == NZBInfo::dsHealth || + nzbInfo->GetDeleteStatus() == NZBInfo::dsBad) { - g_pQueueScriptCoordinator->EnqueueScript(pNZBInfo, QueueScriptCoordinator::qeNzbDeleted); + g_pQueueScriptCoordinator->EnqueueScript(nzbInfo, QueueScriptCoordinator::qeNzbDeleted); } - if (!pNZBInfo->GetPostInfo() && g_pOptions->GetDecode()) + if (!nzbInfo->GetPostInfo() && g_pOptions->GetDecode()) { - pNZBInfo->PrintMessage(Message::mkInfo, "Queueing %s for post-processing", pNZBInfo->GetName()); + nzbInfo->PrintMessage(Message::mkInfo, "Queueing %s for post-processing", nzbInfo->GetName()); - pNZBInfo->EnterPostProcess(); - m_iJobCount++; + nzbInfo->EnterPostProcess(); + m_jobCount++; - if (pNZBInfo->GetParStatus() == NZBInfo::psNone && + if (nzbInfo->GetParStatus() == NZBInfo::psNone && g_pOptions->GetParCheck() != Options::pcAlways && g_pOptions->GetParCheck() != Options::pcForce) { - pNZBInfo->SetParStatus(NZBInfo::psSkipped); + nzbInfo->SetParStatus(NZBInfo::psSkipped); } - if (pNZBInfo->GetRenameStatus() == NZBInfo::rsNone && !g_pOptions->GetParRename()) + if (nzbInfo->GetRenameStatus() == NZBInfo::rsNone && !g_pOptions->GetParRename()) { - pNZBInfo->SetRenameStatus(NZBInfo::rsSkipped); + nzbInfo->SetRenameStatus(NZBInfo::rsSkipped); } - pDownloadQueue->Save(); + downloadQueue->Save(); } else { - NZBCompleted(pDownloadQueue, pNZBInfo, true); + NZBCompleted(downloadQueue, nzbInfo, true); } } -void PrePostProcessor::NZBDeleted(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void PrePostProcessor::NZBDeleted(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { - if (pNZBInfo->GetDeleteStatus() == NZBInfo::dsNone) + if (nzbInfo->GetDeleteStatus() == NZBInfo::dsNone) { - pNZBInfo->SetDeleteStatus(NZBInfo::dsManual); + nzbInfo->SetDeleteStatus(NZBInfo::dsManual); } - pNZBInfo->SetDeleting(false); + nzbInfo->SetDeleting(false); - DeleteCleanup(pNZBInfo); + DeleteCleanup(nzbInfo); - if (pNZBInfo->GetDeleteStatus() == NZBInfo::dsHealth || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsBad) + if (nzbInfo->GetDeleteStatus() == NZBInfo::dsHealth || + nzbInfo->GetDeleteStatus() == NZBInfo::dsBad) { - NZBDownloaded(pDownloadQueue, pNZBInfo); + NZBDownloaded(downloadQueue, nzbInfo); } else { - NZBCompleted(pDownloadQueue, pNZBInfo, true); + NZBCompleted(downloadQueue, nzbInfo, true); } } -void PrePostProcessor::NZBCompleted(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, bool bSaveQueue) +void PrePostProcessor::NZBCompleted(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, bool saveQueue) { - bool bAddToHistory = g_pOptions->GetKeepHistory() > 0 && !pNZBInfo->GetAvoidHistory(); - if (bAddToHistory) + bool addToHistory = g_pOptions->GetKeepHistory() > 0 && !nzbInfo->GetAvoidHistory(); + if (addToHistory) { - g_pHistoryCoordinator->AddToHistory(pDownloadQueue, pNZBInfo); + g_pHistoryCoordinator->AddToHistory(downloadQueue, nzbInfo); } - pNZBInfo->SetAvoidHistory(false); + nzbInfo->SetAvoidHistory(false); - bool bNeedSave = bAddToHistory; + bool needSave = addToHistory; - if (g_pOptions->GetDupeCheck() && pNZBInfo->GetDupeMode() != dmForce && - (pNZBInfo->GetDeleteStatus() == NZBInfo::dsNone || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsHealth || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsBad || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsScan)) + if (g_pOptions->GetDupeCheck() && nzbInfo->GetDupeMode() != dmForce && + (nzbInfo->GetDeleteStatus() == NZBInfo::dsNone || + nzbInfo->GetDeleteStatus() == NZBInfo::dsHealth || + nzbInfo->GetDeleteStatus() == NZBInfo::dsBad || + nzbInfo->GetDeleteStatus() == NZBInfo::dsScan)) { - g_pDupeCoordinator->NZBCompleted(pDownloadQueue, pNZBInfo); - bNeedSave = true; + g_pDupeCoordinator->NZBCompleted(downloadQueue, nzbInfo); + needSave = true; } - if (pNZBInfo->GetDeleteStatus() > NZBInfo::dsNone && - pNZBInfo->GetDeleteStatus() != NZBInfo::dsHealth && - pNZBInfo->GetDeleteStatus() != NZBInfo::dsBad) + if (nzbInfo->GetDeleteStatus() > NZBInfo::dsNone && + nzbInfo->GetDeleteStatus() != NZBInfo::dsHealth && + nzbInfo->GetDeleteStatus() != NZBInfo::dsBad) // nzbs deleted by health check or marked as bad are processed as downloaded with failure status { - g_pQueueScriptCoordinator->EnqueueScript(pNZBInfo, QueueScriptCoordinator::qeNzbDeleted); + g_pQueueScriptCoordinator->EnqueueScript(nzbInfo, QueueScriptCoordinator::qeNzbDeleted); } - if (!bAddToHistory) + if (!addToHistory) { - g_pHistoryCoordinator->DeleteDiskFiles(pNZBInfo); - pDownloadQueue->GetQueue()->Remove(pNZBInfo); - delete pNZBInfo; + g_pHistoryCoordinator->DeleteDiskFiles(nzbInfo); + downloadQueue->GetQueue()->Remove(nzbInfo); + delete nzbInfo; } - if (bSaveQueue && bNeedSave) + if (saveQueue && needSave) { - pDownloadQueue->Save(); + downloadQueue->Save(); } } -void PrePostProcessor::DeleteCleanup(NZBInfo* pNZBInfo) +void PrePostProcessor::DeleteCleanup(NZBInfo* nzbInfo) { - if ((g_pOptions->GetDeleteCleanupDisk() && pNZBInfo->GetCleanupDisk()) || - pNZBInfo->GetDeleteStatus() == NZBInfo::dsDupe) + if ((g_pOptions->GetDeleteCleanupDisk() && nzbInfo->GetCleanupDisk()) || + nzbInfo->GetDeleteStatus() == NZBInfo::dsDupe) { // download was cancelled, deleting already downloaded files from disk - for (CompletedFiles::reverse_iterator it = pNZBInfo->GetCompletedFiles()->rbegin(); it != pNZBInfo->GetCompletedFiles()->rend(); it++) + for (CompletedFiles::reverse_iterator it = nzbInfo->GetCompletedFiles()->rbegin(); it != nzbInfo->GetCompletedFiles()->rend(); it++) { - CompletedFile* pCompletedFile = *it; + CompletedFile* completedFile = *it; - char szFullFileName[1024]; - snprintf(szFullFileName, 1024, "%s%c%s", pNZBInfo->GetDestDir(), (int)PATH_SEPARATOR, pCompletedFile->GetFileName()); - szFullFileName[1024-1] = '\0'; + char fullFileName[1024]; + snprintf(fullFileName, 1024, "%s%c%s", nzbInfo->GetDestDir(), (int)PATH_SEPARATOR, completedFile->GetFileName()); + fullFileName[1024-1] = '\0'; - if (Util::FileExists(szFullFileName)) + if (Util::FileExists(fullFileName)) { - detail("Deleting file %s", pCompletedFile->GetFileName()); - remove(szFullFileName); + detail("Deleting file %s", completedFile->GetFileName()); + remove(fullFileName); } } // delete .out.tmp-files and _brokenlog.txt - DirBrowser dir(pNZBInfo->GetDestDir()); - while (const char* szFilename = dir.Next()) + DirBrowser dir(nzbInfo->GetDestDir()); + while (const char* filename = dir.Next()) { - int iLen = strlen(szFilename); - if ((iLen > 8 && !strcmp(szFilename + iLen - 8, ".out.tmp")) || !strcmp(szFilename, "_brokenlog.txt")) + int len = strlen(filename); + if ((len > 8 && !strcmp(filename + len - 8, ".out.tmp")) || !strcmp(filename, "_brokenlog.txt")) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", pNZBInfo->GetDestDir(), PATH_SEPARATOR, szFilename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", nzbInfo->GetDestDir(), PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - detail("Deleting file %s", szFilename); - remove(szFullFilename); + detail("Deleting file %s", filename); + remove(fullFilename); } } // delete old directory (if empty) - if (Util::DirEmpty(pNZBInfo->GetDestDir())) + if (Util::DirEmpty(nzbInfo->GetDestDir())) { - rmdir(pNZBInfo->GetDestDir()); + rmdir(nzbInfo->GetDestDir()); } } } void PrePostProcessor::CheckPostQueue() { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - if (!m_pCurJob && m_iJobCount > 0) + if (!m_curJob && m_jobCount > 0) { - m_pCurJob = GetNextJob(pDownloadQueue); + m_curJob = GetNextJob(downloadQueue); } - if (m_pCurJob) + if (m_curJob) { - PostInfo* pPostInfo = m_pCurJob->GetPostInfo(); - if (!pPostInfo->GetWorking() && !IsNZBFileDownloading(m_pCurJob)) + PostInfo* postInfo = m_curJob->GetPostInfo(); + if (!postInfo->GetWorking() && !IsNZBFileDownloading(m_curJob)) { #ifndef DISABLE_PARCHECK - if (pPostInfo->GetRequestParCheck() && - (pPostInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped || - (pPostInfo->GetForceRepair() && !pPostInfo->GetNZBInfo()->GetParFull())) && + if (postInfo->GetRequestParCheck() && + (postInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped || + (postInfo->GetForceRepair() && !postInfo->GetNZBInfo()->GetParFull())) && g_pOptions->GetParCheck() != Options::pcManual) { - pPostInfo->SetForceParFull(pPostInfo->GetNZBInfo()->GetParStatus() > NZBInfo::psSkipped); - pPostInfo->GetNZBInfo()->SetParStatus(NZBInfo::psNone); - pPostInfo->SetRequestParCheck(false); - pPostInfo->SetStage(PostInfo::ptQueued); - pPostInfo->GetNZBInfo()->GetScriptStatuses()->Clear(); - DeletePostThread(pPostInfo); + postInfo->SetForceParFull(postInfo->GetNZBInfo()->GetParStatus() > NZBInfo::psSkipped); + postInfo->GetNZBInfo()->SetParStatus(NZBInfo::psNone); + postInfo->SetRequestParCheck(false); + postInfo->SetStage(PostInfo::ptQueued); + postInfo->GetNZBInfo()->GetScriptStatuses()->Clear(); + DeletePostThread(postInfo); } - else if (pPostInfo->GetRequestParCheck() && pPostInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped && + else if (postInfo->GetRequestParCheck() && postInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped && g_pOptions->GetParCheck() == Options::pcManual) { - pPostInfo->SetRequestParCheck(false); - pPostInfo->GetNZBInfo()->SetParStatus(NZBInfo::psManual); - DeletePostThread(pPostInfo); + postInfo->SetRequestParCheck(false); + postInfo->GetNZBInfo()->SetParStatus(NZBInfo::psManual); + DeletePostThread(postInfo); - if (!pPostInfo->GetNZBInfo()->GetFileList()->empty()) + if (!postInfo->GetNZBInfo()->GetFileList()->empty()) { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, - "Downloading all remaining files for manual par-check for %s", pPostInfo->GetNZBInfo()->GetName()); - pDownloadQueue->EditEntry(pPostInfo->GetNZBInfo()->GetID(), DownloadQueue::eaGroupResume, 0, NULL); - pPostInfo->SetStage(PostInfo::ptFinished); + postInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, + "Downloading all remaining files for manual par-check for %s", postInfo->GetNZBInfo()->GetName()); + downloadQueue->EditEntry(postInfo->GetNZBInfo()->GetID(), DownloadQueue::eaGroupResume, 0, NULL); + postInfo->SetStage(PostInfo::ptFinished); } else { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, - "There are no par-files remain for download for %s", pPostInfo->GetNZBInfo()->GetName()); - pPostInfo->SetStage(PostInfo::ptQueued); + postInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, + "There are no par-files remain for download for %s", postInfo->GetNZBInfo()->GetName()); + postInfo->SetStage(PostInfo::ptQueued); } } #endif - if (pPostInfo->GetDeleted()) + if (postInfo->GetDeleted()) { - pPostInfo->SetStage(PostInfo::ptFinished); + postInfo->SetStage(PostInfo::ptFinished); } - if (pPostInfo->GetStage() == PostInfo::ptQueued && - (!g_pOptions->GetPausePostProcess() || pPostInfo->GetNZBInfo()->GetForcePriority())) + if (postInfo->GetStage() == PostInfo::ptQueued && + (!g_pOptions->GetPausePostProcess() || postInfo->GetNZBInfo()->GetForcePriority())) { - DeletePostThread(pPostInfo); - StartJob(pDownloadQueue, pPostInfo); + DeletePostThread(postInfo); + StartJob(downloadQueue, postInfo); } - else if (pPostInfo->GetStage() == PostInfo::ptFinished) + else if (postInfo->GetStage() == PostInfo::ptFinished) { UpdatePauseState(false, NULL); - JobCompleted(pDownloadQueue, pPostInfo); + JobCompleted(downloadQueue, postInfo); } else if (!g_pOptions->GetPausePostProcess()) { @@ -446,22 +446,22 @@ void PrePostProcessor::CheckPostQueue() DownloadQueue::Unlock(); } -NZBInfo* PrePostProcessor::GetNextJob(DownloadQueue* pDownloadQueue) +NZBInfo* PrePostProcessor::GetNextJob(DownloadQueue* downloadQueue) { - NZBInfo* pNZBInfo = NULL; + NZBInfo* nzbInfo = NULL; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo1 = *it; - if (pNZBInfo1->GetPostInfo() && !g_pQueueScriptCoordinator->HasJob(pNZBInfo1->GetID(), NULL) && - (!pNZBInfo || pNZBInfo1->GetPriority() > pNZBInfo->GetPriority()) && - (!g_pOptions->GetPausePostProcess() || pNZBInfo1->GetForcePriority())) + NZBInfo* nzbInfo1 = *it; + if (nzbInfo1->GetPostInfo() && !g_pQueueScriptCoordinator->HasJob(nzbInfo1->GetID(), NULL) && + (!nzbInfo || nzbInfo1->GetPriority() > nzbInfo->GetPriority()) && + (!g_pOptions->GetPausePostProcess() || nzbInfo1->GetForcePriority())) { - pNZBInfo = pNZBInfo1; + nzbInfo = nzbInfo1; } } - return pNZBInfo; + return nzbInfo; } /** @@ -469,248 +469,248 @@ NZBInfo* PrePostProcessor::GetNextJob(DownloadQueue* pDownloadQueue) * delete items which could not be resumed. * Also count the number of post-jobs. */ -void PrePostProcessor::SanitisePostQueue(DownloadQueue* pDownloadQueue) +void PrePostProcessor::SanitisePostQueue(DownloadQueue* downloadQueue) { - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - PostInfo* pPostInfo = pNZBInfo->GetPostInfo(); - if (pPostInfo) + NZBInfo* nzbInfo = *it; + PostInfo* postInfo = nzbInfo->GetPostInfo(); + if (postInfo) { - m_iJobCount++; - if (pPostInfo->GetStage() == PostInfo::ptExecutingScript || - !Util::DirectoryExists(pNZBInfo->GetDestDir())) + m_jobCount++; + if (postInfo->GetStage() == PostInfo::ptExecutingScript || + !Util::DirectoryExists(nzbInfo->GetDestDir())) { - pPostInfo->SetStage(PostInfo::ptFinished); + postInfo->SetStage(PostInfo::ptFinished); } else { - pPostInfo->SetStage(PostInfo::ptQueued); + postInfo->SetStage(PostInfo::ptQueued); } } } } -void PrePostProcessor::DeletePostThread(PostInfo* pPostInfo) +void PrePostProcessor::DeletePostThread(PostInfo* postInfo) { - delete pPostInfo->GetPostThread(); - pPostInfo->SetPostThread(NULL); + delete postInfo->GetPostThread(); + postInfo->SetPostThread(NULL); } -void PrePostProcessor::StartJob(DownloadQueue* pDownloadQueue, PostInfo* pPostInfo) +void PrePostProcessor::StartJob(DownloadQueue* downloadQueue, PostInfo* postInfo) { - if (!pPostInfo->GetStartTime()) + if (!postInfo->GetStartTime()) { - pPostInfo->SetStartTime(time(NULL)); + postInfo->SetStartTime(time(NULL)); } #ifndef DISABLE_PARCHECK - if (pPostInfo->GetNZBInfo()->GetRenameStatus() == NZBInfo::rsNone && - pPostInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone) + if (postInfo->GetNZBInfo()->GetRenameStatus() == NZBInfo::rsNone && + postInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone) { UpdatePauseState(g_pOptions->GetParPauseQueue(), "par-rename"); - m_ParCoordinator.StartParRenameJob(pPostInfo); + m_parCoordinator.StartParRenameJob(postInfo); return; } - else if (pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psNone && - pPostInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone) + else if (postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psNone && + postInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone) { - if (ParParser::FindMainPars(pPostInfo->GetNZBInfo()->GetDestDir(), NULL)) + if (ParParser::FindMainPars(postInfo->GetNZBInfo()->GetDestDir(), NULL)) { UpdatePauseState(g_pOptions->GetParPauseQueue(), "par-check"); - m_ParCoordinator.StartParCheckJob(pPostInfo); + m_parCoordinator.StartParCheckJob(postInfo); } else { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, - "Nothing to par-check for %s", pPostInfo->GetNZBInfo()->GetName()); - pPostInfo->GetNZBInfo()->SetParStatus(NZBInfo::psSkipped); - pPostInfo->SetWorking(false); - pPostInfo->SetStage(PostInfo::ptQueued); + postInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, + "Nothing to par-check for %s", postInfo->GetNZBInfo()->GetName()); + postInfo->GetNZBInfo()->SetParStatus(NZBInfo::psSkipped); + postInfo->SetWorking(false); + postInfo->SetStage(PostInfo::ptQueued); } return; } - else if (pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSkipped && + else if (postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSkipped && ((g_pOptions->GetParScan() != Options::psDupe && - pPostInfo->GetNZBInfo()->CalcHealth() < pPostInfo->GetNZBInfo()->CalcCriticalHealth(false) && - pPostInfo->GetNZBInfo()->CalcCriticalHealth(false) < 1000) || - pPostInfo->GetNZBInfo()->CalcHealth() == 0) && - ParParser::FindMainPars(pPostInfo->GetNZBInfo()->GetDestDir(), NULL)) + postInfo->GetNZBInfo()->CalcHealth() < postInfo->GetNZBInfo()->CalcCriticalHealth(false) && + postInfo->GetNZBInfo()->CalcCriticalHealth(false) < 1000) || + postInfo->GetNZBInfo()->CalcHealth() == 0) && + ParParser::FindMainPars(postInfo->GetNZBInfo()->GetDestDir(), NULL)) { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, - pPostInfo->GetNZBInfo()->CalcHealth() == 0 ? + postInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, + postInfo->GetNZBInfo()->CalcHealth() == 0 ? "Skipping par-check for %s due to health 0%%" : "Skipping par-check for %s due to health %.1f%% below critical %.1f%%", - pPostInfo->GetNZBInfo()->GetName(), - pPostInfo->GetNZBInfo()->CalcHealth() / 10.0, pPostInfo->GetNZBInfo()->CalcCriticalHealth(false) / 10.0); - pPostInfo->GetNZBInfo()->SetParStatus(NZBInfo::psFailure); + postInfo->GetNZBInfo()->GetName(), + postInfo->GetNZBInfo()->CalcHealth() / 10.0, postInfo->GetNZBInfo()->CalcCriticalHealth(false) / 10.0); + postInfo->GetNZBInfo()->SetParStatus(NZBInfo::psFailure); return; } - else if (pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSkipped && - pPostInfo->GetNZBInfo()->GetFailedSize() - pPostInfo->GetNZBInfo()->GetParFailedSize() > 0 && - ParParser::FindMainPars(pPostInfo->GetNZBInfo()->GetDestDir(), NULL)) + else if (postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSkipped && + postInfo->GetNZBInfo()->GetFailedSize() - postInfo->GetNZBInfo()->GetParFailedSize() > 0 && + ParParser::FindMainPars(postInfo->GetNZBInfo()->GetDestDir(), NULL)) { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, + postInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, "Collection %s with health %.1f%% needs par-check", - pPostInfo->GetNZBInfo()->GetName(), pPostInfo->GetNZBInfo()->CalcHealth() / 10.0); - pPostInfo->SetRequestParCheck(true); + postInfo->GetNZBInfo()->GetName(), postInfo->GetNZBInfo()->CalcHealth() / 10.0); + postInfo->SetRequestParCheck(true); return; } #endif - NZBParameter* pUnpackParameter = pPostInfo->GetNZBInfo()->GetParameters()->Find("*Unpack:", false); - bool bUnpackParam = !(pUnpackParameter && !strcasecmp(pUnpackParameter->GetValue(), "no")); - bool bUnpack = bUnpackParam && pPostInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usNone && - pPostInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone; + NZBParameter* unpackParameter = postInfo->GetNZBInfo()->GetParameters()->Find("*Unpack:", false); + bool unpackParam = !(unpackParameter && !strcasecmp(unpackParameter->GetValue(), "no")); + bool unpack = unpackParam && postInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usNone && + postInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone; - bool bParFailed = pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psFailure || - pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psRepairPossible || - pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psManual; + bool parFailed = postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psFailure || + postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psRepairPossible || + postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psManual; - bool bCleanup = !bUnpack && - pPostInfo->GetNZBInfo()->GetCleanupStatus() == NZBInfo::csNone && + bool cleanup = !unpack && + postInfo->GetNZBInfo()->GetCleanupStatus() == NZBInfo::csNone && !Util::EmptyStr(g_pOptions->GetExtCleanupDisk()) && - ((pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSuccess && - pPostInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usFailure && - pPostInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usSpace && - pPostInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usPassword) || - (pPostInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usSuccess && - pPostInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psFailure) || - ((pPostInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usNone || - pPostInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usSkipped) && - (pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psNone || - pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSkipped) && - pPostInfo->GetNZBInfo()->CalcHealth() == 1000)); + ((postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSuccess && + postInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usFailure && + postInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usSpace && + postInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usPassword) || + (postInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usSuccess && + postInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psFailure) || + ((postInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usNone || + postInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usSkipped) && + (postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psNone || + postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSkipped) && + postInfo->GetNZBInfo()->CalcHealth() == 1000)); - bool bMoveInter = !bUnpack && - pPostInfo->GetNZBInfo()->GetMoveStatus() == NZBInfo::msNone && - pPostInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usFailure && - pPostInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usSpace && - pPostInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usPassword && - pPostInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psFailure && - pPostInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psManual && - pPostInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone && + bool moveInter = !unpack && + postInfo->GetNZBInfo()->GetMoveStatus() == NZBInfo::msNone && + postInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usFailure && + postInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usSpace && + postInfo->GetNZBInfo()->GetUnpackStatus() != NZBInfo::usPassword && + postInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psFailure && + postInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psManual && + postInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsNone && !Util::EmptyStr(g_pOptions->GetInterDir()) && - !strncmp(pPostInfo->GetNZBInfo()->GetDestDir(), g_pOptions->GetInterDir(), strlen(g_pOptions->GetInterDir())); + !strncmp(postInfo->GetNZBInfo()->GetDestDir(), g_pOptions->GetInterDir(), strlen(g_pOptions->GetInterDir())); - bool bPostScript = true; + bool postScript = true; - if (bUnpack && bParFailed) + if (unpack && parFailed) { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, - "Skipping unpack for %s due to %s", pPostInfo->GetNZBInfo()->GetName(), - pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psManual ? "required par-repair" : "par-failure"); - pPostInfo->GetNZBInfo()->SetUnpackStatus(NZBInfo::usSkipped); - bUnpack = false; + postInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, + "Skipping unpack for %s due to %s", postInfo->GetNZBInfo()->GetName(), + postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psManual ? "required par-repair" : "par-failure"); + postInfo->GetNZBInfo()->SetUnpackStatus(NZBInfo::usSkipped); + unpack = false; } - if (!bUnpack && !bMoveInter && !bPostScript) + if (!unpack && !moveInter && !postScript) { - pPostInfo->SetStage(PostInfo::ptFinished); + postInfo->SetStage(PostInfo::ptFinished); return; } - pPostInfo->SetProgressLabel(bUnpack ? "Unpacking" : bMoveInter ? "Moving" : "Executing post-process-script"); - pPostInfo->SetWorking(true); - pPostInfo->SetStage(bUnpack ? PostInfo::ptUnpacking : bMoveInter ? PostInfo::ptMoving : PostInfo::ptExecutingScript); - pPostInfo->SetFileProgress(0); - pPostInfo->SetStageProgress(0); + postInfo->SetProgressLabel(unpack ? "Unpacking" : moveInter ? "Moving" : "Executing post-process-script"); + postInfo->SetWorking(true); + postInfo->SetStage(unpack ? PostInfo::ptUnpacking : moveInter ? PostInfo::ptMoving : PostInfo::ptExecutingScript); + postInfo->SetFileProgress(0); + postInfo->SetStageProgress(0); - pDownloadQueue->Save(); + downloadQueue->Save(); - pPostInfo->SetStageTime(time(NULL)); + postInfo->SetStageTime(time(NULL)); - if (bUnpack) + if (unpack) { UpdatePauseState(g_pOptions->GetUnpackPauseQueue(), "unpack"); - UnpackController::StartJob(pPostInfo); + UnpackController::StartJob(postInfo); } - else if (bCleanup) + else if (cleanup) { UpdatePauseState(g_pOptions->GetUnpackPauseQueue() || g_pOptions->GetScriptPauseQueue(), "cleanup"); - CleanupController::StartJob(pPostInfo); + CleanupController::StartJob(postInfo); } - else if (bMoveInter) + else if (moveInter) { UpdatePauseState(g_pOptions->GetUnpackPauseQueue() || g_pOptions->GetScriptPauseQueue(), "move"); - MoveController::StartJob(pPostInfo); + MoveController::StartJob(postInfo); } else { UpdatePauseState(g_pOptions->GetScriptPauseQueue(), "post-process-script"); - PostScriptController::StartJob(pPostInfo); + PostScriptController::StartJob(postInfo); } } -void PrePostProcessor::JobCompleted(DownloadQueue* pDownloadQueue, PostInfo* pPostInfo) +void PrePostProcessor::JobCompleted(DownloadQueue* downloadQueue, PostInfo* postInfo) { - NZBInfo* pNZBInfo = pPostInfo->GetNZBInfo(); + NZBInfo* nzbInfo = postInfo->GetNZBInfo(); - if (pPostInfo->GetStartTime() > 0) + if (postInfo->GetStartTime() > 0) { - pNZBInfo->SetPostTotalSec((int)(time(NULL) - pPostInfo->GetStartTime())); - pPostInfo->SetStartTime(0); + nzbInfo->SetPostTotalSec((int)(time(NULL) - postInfo->GetStartTime())); + postInfo->SetStartTime(0); } - DeletePostThread(pPostInfo); - pNZBInfo->LeavePostProcess(); + DeletePostThread(postInfo); + nzbInfo->LeavePostProcess(); - if (IsNZBFileCompleted(pNZBInfo, true, false)) + if (IsNZBFileCompleted(nzbInfo, true, false)) { // Cleaning up queue if par-check was successful or unpack was successful or // health is 100% (if unpack and par-check were not performed) // or health is below critical health - bool bCanCleanupQueue = - ((pNZBInfo->GetParStatus() == NZBInfo::psSuccess || - pNZBInfo->GetParStatus() == NZBInfo::psRepairPossible) && - pNZBInfo->GetUnpackStatus() != NZBInfo::usFailure && - pNZBInfo->GetUnpackStatus() != NZBInfo::usSpace && - pNZBInfo->GetUnpackStatus() != NZBInfo::usPassword) || - (pNZBInfo->GetUnpackStatus() == NZBInfo::usSuccess && - pNZBInfo->GetParStatus() != NZBInfo::psFailure) || - (pNZBInfo->GetUnpackStatus() <= NZBInfo::usSkipped && - pNZBInfo->GetParStatus() != NZBInfo::psFailure && - pNZBInfo->GetFailedSize() - pNZBInfo->GetParFailedSize() == 0) || - (pNZBInfo->CalcHealth() < pNZBInfo->CalcCriticalHealth(false) && - pNZBInfo->CalcCriticalHealth(false) < 1000); - if (g_pOptions->GetParCleanupQueue() && bCanCleanupQueue && !pNZBInfo->GetFileList()->empty()) + bool canCleanupQueue = + ((nzbInfo->GetParStatus() == NZBInfo::psSuccess || + nzbInfo->GetParStatus() == NZBInfo::psRepairPossible) && + nzbInfo->GetUnpackStatus() != NZBInfo::usFailure && + nzbInfo->GetUnpackStatus() != NZBInfo::usSpace && + nzbInfo->GetUnpackStatus() != NZBInfo::usPassword) || + (nzbInfo->GetUnpackStatus() == NZBInfo::usSuccess && + nzbInfo->GetParStatus() != NZBInfo::psFailure) || + (nzbInfo->GetUnpackStatus() <= NZBInfo::usSkipped && + nzbInfo->GetParStatus() != NZBInfo::psFailure && + nzbInfo->GetFailedSize() - nzbInfo->GetParFailedSize() == 0) || + (nzbInfo->CalcHealth() < nzbInfo->CalcCriticalHealth(false) && + nzbInfo->CalcCriticalHealth(false) < 1000); + if (g_pOptions->GetParCleanupQueue() && canCleanupQueue && !nzbInfo->GetFileList()->empty()) { - pNZBInfo->PrintMessage(Message::mkInfo, "Cleaning up download queue for %s", pNZBInfo->GetName()); - pNZBInfo->SetParCleanup(true); - pDownloadQueue->EditEntry(pNZBInfo->GetID(), DownloadQueue::eaGroupDelete, 0, NULL); + nzbInfo->PrintMessage(Message::mkInfo, "Cleaning up download queue for %s", nzbInfo->GetName()); + nzbInfo->SetParCleanup(true); + downloadQueue->EditEntry(nzbInfo->GetID(), DownloadQueue::eaGroupDelete, 0, NULL); } - if (pNZBInfo->GetUnpackCleanedUpDisk()) + if (nzbInfo->GetUnpackCleanedUpDisk()) { - pNZBInfo->ClearCompletedFiles(); + nzbInfo->ClearCompletedFiles(); } - NZBCompleted(pDownloadQueue, pNZBInfo, false); + NZBCompleted(downloadQueue, nzbInfo, false); } - if (pNZBInfo == m_pCurJob) + if (nzbInfo == m_curJob) { - m_pCurJob = NULL; + m_curJob = NULL; } - m_iJobCount--; + m_jobCount--; - pDownloadQueue->Save(); + downloadQueue->Save(); } -bool PrePostProcessor::IsNZBFileCompleted(NZBInfo* pNZBInfo, bool bIgnorePausedPars, bool bAllowOnlyOneDeleted) +bool PrePostProcessor::IsNZBFileCompleted(NZBInfo* nzbInfo, bool ignorePausedPars, bool allowOnlyOneDeleted) { - int iDeleted = 0; + int deleted = 0; - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - if (pFileInfo->GetDeleted()) + FileInfo* fileInfo = *it; + if (fileInfo->GetDeleted()) { - iDeleted++; + deleted++; } - if (((!pFileInfo->GetPaused() || !bIgnorePausedPars || !pFileInfo->GetParFile()) && - !pFileInfo->GetDeleted()) || - (bAllowOnlyOneDeleted && iDeleted > 1)) + if (((!fileInfo->GetPaused() || !ignorePausedPars || !fileInfo->GetParFile()) && + !fileInfo->GetDeleted()) || + (allowOnlyOneDeleted && deleted > 1)) { return false; } @@ -719,17 +719,17 @@ bool PrePostProcessor::IsNZBFileCompleted(NZBInfo* pNZBInfo, bool bIgnorePausedP return true; } -bool PrePostProcessor::IsNZBFileDownloading(NZBInfo* pNZBInfo) +bool PrePostProcessor::IsNZBFileDownloading(NZBInfo* nzbInfo) { - if (pNZBInfo->GetActiveDownloads()) + if (nzbInfo->GetActiveDownloads()) { return true; } - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - if (!pFileInfo->GetPaused()) + FileInfo* fileInfo = *it; + if (!fileInfo->GetPaused()) { return true; } @@ -738,67 +738,67 @@ bool PrePostProcessor::IsNZBFileDownloading(NZBInfo* pNZBInfo) return false; } -void PrePostProcessor::UpdatePauseState(bool bNeedPause, const char* szReason) +void PrePostProcessor::UpdatePauseState(bool needPause, const char* reason) { - if (bNeedPause && !g_pOptions->GetTempPauseDownload()) + if (needPause && !g_pOptions->GetTempPauseDownload()) { - info("Pausing download before %s", szReason); + info("Pausing download before %s", reason); } - else if (!bNeedPause && g_pOptions->GetTempPauseDownload()) + else if (!needPause && g_pOptions->GetTempPauseDownload()) { - info("Unpausing download after %s", m_szPauseReason); + info("Unpausing download after %s", m_pauseReason); } - g_pOptions->SetTempPauseDownload(bNeedPause); - m_szPauseReason = szReason; + g_pOptions->SetTempPauseDownload(needPause); + m_pauseReason = reason; } -bool PrePostProcessor::EditList(DownloadQueue* pDownloadQueue, IDList* pIDList, DownloadQueue::EEditAction eAction, int iOffset, const char* szText) +bool PrePostProcessor::EditList(DownloadQueue* downloadQueue, IDList* idList, DownloadQueue::EEditAction action, int offset, const char* text) { debug("Edit-command for post-processor received"); - switch (eAction) + switch (action) { case DownloadQueue::eaPostDelete: - return PostQueueDelete(pDownloadQueue, pIDList); + return PostQueueDelete(downloadQueue, idList); default: return false; } } -bool PrePostProcessor::PostQueueDelete(DownloadQueue* pDownloadQueue, IDList* pIDList) +bool PrePostProcessor::PostQueueDelete(DownloadQueue* downloadQueue, IDList* idList) { - bool bOK = false; + bool ok = false; - for (IDList::iterator itID = pIDList->begin(); itID != pIDList->end(); itID++) + for (IDList::iterator itID = idList->begin(); itID != idList->end(); itID++) { - int iID = *itID; + int id = *itID; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - PostInfo* pPostInfo = pNZBInfo->GetPostInfo(); - if (pPostInfo && pNZBInfo->GetID() == iID) + NZBInfo* nzbInfo = *it; + PostInfo* postInfo = nzbInfo->GetPostInfo(); + if (postInfo && nzbInfo->GetID() == id) { - if (pPostInfo->GetWorking()) + if (postInfo->GetWorking()) { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, - "Deleting active post-job %s", pPostInfo->GetNZBInfo()->GetName()); - pPostInfo->SetDeleted(true); + postInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, + "Deleting active post-job %s", postInfo->GetNZBInfo()->GetName()); + postInfo->SetDeleted(true); #ifndef DISABLE_PARCHECK - if (PostInfo::ptLoadingPars <= pPostInfo->GetStage() && pPostInfo->GetStage() <= PostInfo::ptRenaming) + if (PostInfo::ptLoadingPars <= postInfo->GetStage() && postInfo->GetStage() <= PostInfo::ptRenaming) { - if (m_ParCoordinator.Cancel()) + if (m_parCoordinator.Cancel()) { - bOK = true; + ok = true; } } else #endif - if (pPostInfo->GetPostThread()) + if (postInfo->GetPostThread()) { - debug("Terminating %s for %s", (pPostInfo->GetStage() == PostInfo::ptUnpacking ? "unpack" : "post-process-script"), pPostInfo->GetNZBInfo()->GetName()); - pPostInfo->GetPostThread()->Stop(); - bOK = true; + debug("Terminating %s for %s", (postInfo->GetStage() == PostInfo::ptUnpacking ? "unpack" : "post-process-script"), postInfo->GetNZBInfo()->GetName()); + postInfo->GetPostThread()->Stop(); + ok = true; } else { @@ -807,15 +807,15 @@ bool PrePostProcessor::PostQueueDelete(DownloadQueue* pDownloadQueue, IDList* pI } else { - pPostInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, - "Deleting queued post-job %s", pPostInfo->GetNZBInfo()->GetName()); - JobCompleted(pDownloadQueue, pPostInfo); - bOK = true; + postInfo->GetNZBInfo()->PrintMessage(Message::mkInfo, + "Deleting queued post-job %s", postInfo->GetNZBInfo()->GetName()); + JobCompleted(downloadQueue, postInfo); + ok = true; } break; } } } - return bOK; + return ok; } diff --git a/daemon/postprocess/PrePostProcessor.h b/daemon/postprocess/PrePostProcessor.h index 8931c1bd..14f39790 100644 --- a/daemon/postprocess/PrePostProcessor.h +++ b/daemon/postprocess/PrePostProcessor.h @@ -39,44 +39,44 @@ private: class DownloadQueueObserver: public Observer { public: - PrePostProcessor* m_pOwner; - virtual void Update(Subject* Caller, void* Aspect) { m_pOwner->DownloadQueueUpdate(Caller, Aspect); } + PrePostProcessor* m_owner; + virtual void Update(Subject* Caller, void* Aspect) { m_owner->DownloadQueueUpdate(Caller, Aspect); } }; private: - ParCoordinator m_ParCoordinator; - DownloadQueueObserver m_DownloadQueueObserver; - int m_iJobCount; - NZBInfo* m_pCurJob; - const char* m_szPauseReason; + ParCoordinator m_parCoordinator; + DownloadQueueObserver m_downloadQueueObserver; + int m_jobCount; + NZBInfo* m_curJob; + const char* m_pauseReason; - bool IsNZBFileCompleted(NZBInfo* pNZBInfo, bool bIgnorePausedPars, bool bAllowOnlyOneDeleted); - bool IsNZBFileDownloading(NZBInfo* pNZBInfo); + bool IsNZBFileCompleted(NZBInfo* nzbInfo, bool ignorePausedPars, bool allowOnlyOneDeleted); + bool IsNZBFileDownloading(NZBInfo* nzbInfo); void CheckPostQueue(); - void JobCompleted(DownloadQueue* pDownloadQueue, PostInfo* pPostInfo); - void StartJob(DownloadQueue* pDownloadQueue, PostInfo* pPostInfo); - void SaveQueue(DownloadQueue* pDownloadQueue); - void SanitisePostQueue(DownloadQueue* pDownloadQueue); - void UpdatePauseState(bool bNeedPause, const char* szReason); - void NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); - void NZBDeleted(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); - void NZBCompleted(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, bool bSaveQueue); - bool PostQueueDelete(DownloadQueue* pDownloadQueue, IDList* pIDList); - void DeletePostThread(PostInfo* pPostInfo); - NZBInfo* GetNextJob(DownloadQueue* pDownloadQueue); + void JobCompleted(DownloadQueue* downloadQueue, PostInfo* postInfo); + void StartJob(DownloadQueue* downloadQueue, PostInfo* postInfo); + void SaveQueue(DownloadQueue* downloadQueue); + void SanitisePostQueue(DownloadQueue* downloadQueue); + void UpdatePauseState(bool needPause, const char* reason); + void NZBFound(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); + void NZBDeleted(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); + void NZBCompleted(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, bool saveQueue); + bool PostQueueDelete(DownloadQueue* downloadQueue, IDList* idList); + void DeletePostThread(PostInfo* postInfo); + NZBInfo* GetNextJob(DownloadQueue* downloadQueue); void DownloadQueueUpdate(Subject* Caller, void* Aspect); - void DeleteCleanup(NZBInfo* pNZBInfo); + void DeleteCleanup(NZBInfo* nzbInfo); public: PrePostProcessor(); virtual ~PrePostProcessor(); virtual void Run(); virtual void Stop(); - bool HasMoreJobs() { return m_iJobCount > 0; } - int GetJobCount() { return m_iJobCount; } - bool EditList(DownloadQueue* pDownloadQueue, IDList* pIDList, DownloadQueue::EEditAction eAction, int iOffset, const char* szText); - void NZBAdded(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); - void NZBDownloaded(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); + bool HasMoreJobs() { return m_jobCount > 0; } + int GetJobCount() { return m_jobCount; } + bool EditList(DownloadQueue* downloadQueue, IDList* idList, DownloadQueue::EEditAction action, int offset, const char* text); + void NZBAdded(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); + void NZBDownloaded(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); }; extern PrePostProcessor* g_pPrePostProcessor; diff --git a/daemon/postprocess/Unpack.cpp b/daemon/postprocess/Unpack.cpp index d944496e..69f60184 100644 --- a/daemon/postprocess/Unpack.cpp +++ b/daemon/postprocess/Unpack.cpp @@ -56,12 +56,12 @@ void UnpackController::FileList::Clear() clear(); } -bool UnpackController::FileList::Exists(const char* szFilename) +bool UnpackController::FileList::Exists(const char* filename) { for (iterator it = begin(); it != end(); it++) { - char* szFilename1 = *it; - if (!strcmp(szFilename1, szFilename)) + char* filename1 = *it; + if (!strcmp(filename1, filename)) { return true; } @@ -78,12 +78,12 @@ UnpackController::ParamList::~ParamList() } } -bool UnpackController::ParamList::Exists(const char* szParam) +bool UnpackController::ParamList::Exists(const char* param) { for (iterator it = begin(); it != end(); it++) { - char* szParam1 = *it; - if (!strcmp(szParam1, szParam)) + char* param1 = *it; + if (!strcmp(param1, param)) { return true; } @@ -92,147 +92,147 @@ bool UnpackController::ParamList::Exists(const char* szParam) return false; } -void UnpackController::StartJob(PostInfo* pPostInfo) +void UnpackController::StartJob(PostInfo* postInfo) { - UnpackController* pUnpackController = new UnpackController(); - pUnpackController->m_pPostInfo = pPostInfo; - pUnpackController->SetAutoDestroy(false); + UnpackController* unpackController = new UnpackController(); + unpackController->m_postInfo = postInfo; + unpackController->SetAutoDestroy(false); - pPostInfo->SetPostThread(pUnpackController); + postInfo->SetPostThread(unpackController); - pUnpackController->Start(); + unpackController->Start(); } void UnpackController::Run() { - time_t tStart = time(NULL); + time_t start = time(NULL); // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); - strncpy(m_szDestDir, m_pPostInfo->GetNZBInfo()->GetDestDir(), 1024); - m_szDestDir[1024-1] = '\0'; + strncpy(m_destDir, m_postInfo->GetNZBInfo()->GetDestDir(), 1024); + m_destDir[1024-1] = '\0'; - strncpy(m_szName, m_pPostInfo->GetNZBInfo()->GetName(), 1024); - m_szName[1024-1] = '\0'; + strncpy(m_name, m_postInfo->GetNZBInfo()->GetName(), 1024); + m_name[1024-1] = '\0'; - m_bCleanedUpDisk = false; - m_szPassword[0] = '\0'; - m_szFinalDir[0] = '\0'; - m_bFinalDirCreated = false; - m_bUnpackOK = true; - m_bUnpackStartError = false; - m_bUnpackSpaceError = false; - m_bUnpackDecryptError = false; - m_bUnpackPasswordError = false; - m_bAutoTerminated = false; - m_bPassListTried = false; + m_cleanedUpDisk = false; + m_password[0] = '\0'; + m_finalDir[0] = '\0'; + m_finalDirCreated = false; + m_unpackOK = true; + m_unpackStartError = false; + m_unpackSpaceError = false; + m_unpackDecryptError = false; + m_unpackPasswordError = false; + m_autoTerminated = false; + m_passListTried = false; - NZBParameter* pParameter = m_pPostInfo->GetNZBInfo()->GetParameters()->Find("*Unpack:", false); - bool bUnpack = !(pParameter && !strcasecmp(pParameter->GetValue(), "no")); + NZBParameter* parameter = m_postInfo->GetNZBInfo()->GetParameters()->Find("*Unpack:", false); + bool unpack = !(parameter && !strcasecmp(parameter->GetValue(), "no")); - pParameter = m_pPostInfo->GetNZBInfo()->GetParameters()->Find("*Unpack:Password", false); - if (pParameter) + parameter = m_postInfo->GetNZBInfo()->GetParameters()->Find("*Unpack:Password", false); + if (parameter) { - strncpy(m_szPassword, pParameter->GetValue(), 1024-1); - m_szPassword[1024-1] = '\0'; + strncpy(m_password, parameter->GetValue(), 1024-1); + m_password[1024-1] = '\0'; } DownloadQueue::Unlock(); - snprintf(m_szInfoName, 1024, "unpack for %s", m_szName); - m_szInfoName[1024-1] = '\0'; + snprintf(m_infoName, 1024, "unpack for %s", m_name); + m_infoName[1024-1] = '\0'; - snprintf(m_szInfoNameUp, 1024, "Unpack for %s", m_szName); // first letter in upper case - m_szInfoNameUp[1024-1] = '\0'; + snprintf(m_infoNameUp, 1024, "Unpack for %s", m_name); // first letter in upper case + m_infoNameUp[1024-1] = '\0'; - m_bHasParFiles = ParParser::FindMainPars(m_szDestDir, NULL); + m_hasParFiles = ParParser::FindMainPars(m_destDir, NULL); - if (bUnpack) + if (unpack) { - bool bScanNonStdFiles = m_pPostInfo->GetNZBInfo()->GetRenameStatus() > NZBInfo::rsSkipped || - m_pPostInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSuccess || - !m_bHasParFiles; - CheckArchiveFiles(bScanNonStdFiles); + bool scanNonStdFiles = m_postInfo->GetNZBInfo()->GetRenameStatus() > NZBInfo::rsSkipped || + m_postInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psSuccess || + !m_hasParFiles; + CheckArchiveFiles(scanNonStdFiles); } - SetInfoName(m_szInfoName); - SetWorkingDir(m_szDestDir); + SetInfoName(m_infoName); + SetWorkingDir(m_destDir); - bool bHasFiles = m_bHasRarFiles || m_bHasNonStdRarFiles || m_bHasSevenZipFiles || m_bHasSevenZipMultiFiles || m_bHasSplittedFiles; + bool hasFiles = m_hasRarFiles || m_hasNonStdRarFiles || m_hasSevenZipFiles || m_hasSevenZipMultiFiles || m_hasSplittedFiles; - if (m_pPostInfo->GetUnpackTried() && !m_pPostInfo->GetParRepaired() && - (!Util::EmptyStr(m_szPassword) || Util::EmptyStr(g_pOptions->GetUnpackPassFile()) || m_pPostInfo->GetPassListTried())) + if (m_postInfo->GetUnpackTried() && !m_postInfo->GetParRepaired() && + (!Util::EmptyStr(m_password) || Util::EmptyStr(g_pOptions->GetUnpackPassFile()) || m_postInfo->GetPassListTried())) { - PrintMessage(Message::mkInfo, "Second unpack attempt skipped for %s due to par-check not repaired anything", m_szName); + PrintMessage(Message::mkInfo, "Second unpack attempt skipped for %s due to par-check not repaired anything", m_name); PrintMessage(Message::mkError, - m_pPostInfo->GetLastUnpackStatus() == (int)NZBInfo::usPassword ? + m_postInfo->GetLastUnpackStatus() == (int)NZBInfo::usPassword ? "%s failed: checksum error in the encrypted file. Corrupt file or wrong password." : "%s failed.", - m_szInfoNameUp); - m_pPostInfo->GetNZBInfo()->SetUnpackStatus((NZBInfo::EUnpackStatus)m_pPostInfo->GetLastUnpackStatus()); - m_pPostInfo->SetStage(PostInfo::ptQueued); + m_infoNameUp); + m_postInfo->GetNZBInfo()->SetUnpackStatus((NZBInfo::EUnpackStatus)m_postInfo->GetLastUnpackStatus()); + m_postInfo->SetStage(PostInfo::ptQueued); } - else if (bUnpack && bHasFiles) + else if (unpack && hasFiles) { - PrintMessage(Message::mkInfo, "Unpacking %s", m_szName); + PrintMessage(Message::mkInfo, "Unpacking %s", m_name); CreateUnpackDir(); - if (m_bHasRarFiles || m_bHasNonStdRarFiles) + if (m_hasRarFiles || m_hasNonStdRarFiles) { UnpackArchives(upUnrar, false); } - if (m_bHasSevenZipFiles && m_bUnpackOK) + if (m_hasSevenZipFiles && m_unpackOK) { UnpackArchives(upSevenZip, false); } - if (m_bHasSevenZipMultiFiles && m_bUnpackOK) + if (m_hasSevenZipMultiFiles && m_unpackOK) { UnpackArchives(upSevenZip, true); } - if (m_bHasSplittedFiles && m_bUnpackOK) + if (m_hasSplittedFiles && m_unpackOK) { JoinSplittedFiles(); } Completed(); - m_JoinedFiles.Clear(); + m_joinedFiles.Clear(); } else { - PrintMessage(Message::mkInfo, (bUnpack ? "Nothing to unpack for %s" : "Unpack for %s skipped"), m_szName); + PrintMessage(Message::mkInfo, (unpack ? "Nothing to unpack for %s" : "Unpack for %s skipped"), m_name); #ifndef DISABLE_PARCHECK - if (bUnpack && m_pPostInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped && - m_pPostInfo->GetNZBInfo()->GetRenameStatus() <= NZBInfo::rsSkipped && m_bHasParFiles) + if (unpack && m_postInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped && + m_postInfo->GetNZBInfo()->GetRenameStatus() <= NZBInfo::rsSkipped && m_hasParFiles) { RequestParCheck(false); } else #endif { - m_pPostInfo->GetNZBInfo()->SetUnpackStatus(NZBInfo::usSkipped); - m_pPostInfo->SetStage(PostInfo::ptQueued); + m_postInfo->GetNZBInfo()->SetUnpackStatus(NZBInfo::usSkipped); + m_postInfo->SetStage(PostInfo::ptQueued); } } - int iUnpackSec = (int)(time(NULL) - tStart); - m_pPostInfo->GetNZBInfo()->SetUnpackSec(m_pPostInfo->GetNZBInfo()->GetUnpackSec() + iUnpackSec); + int unpackSec = (int)(time(NULL) - start); + m_postInfo->GetNZBInfo()->SetUnpackSec(m_postInfo->GetNZBInfo()->GetUnpackSec() + unpackSec); - m_pPostInfo->SetWorking(false); + m_postInfo->SetWorking(false); } -void UnpackController::UnpackArchives(EUnpacker eUnpacker, bool bMultiVolumes) +void UnpackController::UnpackArchives(EUnpacker unpacker, bool multiVolumes) { - if (!m_pPostInfo->GetUnpackTried() || m_pPostInfo->GetParRepaired()) + if (!m_postInfo->GetUnpackTried() || m_postInfo->GetParRepaired()) { - ExecuteUnpack(eUnpacker, m_szPassword, bMultiVolumes); - if (!m_bUnpackOK && m_bHasParFiles && !m_bUnpackPasswordError && - m_pPostInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped) + ExecuteUnpack(unpacker, m_password, multiVolumes); + if (!m_unpackOK && m_hasParFiles && !m_unpackPasswordError && + m_postInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped) { // for rar4- or 7z-archives try par-check first, before trying password file return; @@ -240,14 +240,14 @@ void UnpackController::UnpackArchives(EUnpacker eUnpacker, bool bMultiVolumes) } else { - m_bUnpackOK = false; - m_bUnpackDecryptError = m_pPostInfo->GetLastUnpackStatus() == (int)NZBInfo::usPassword; + m_unpackOK = false; + m_unpackDecryptError = m_postInfo->GetLastUnpackStatus() == (int)NZBInfo::usPassword; } - if (!m_bUnpackOK && !m_bUnpackStartError && !m_bUnpackSpaceError && - (m_bUnpackDecryptError || m_bUnpackPasswordError) && - (!GetTerminated() || m_bAutoTerminated) && - Util::EmptyStr(m_szPassword) && !Util::EmptyStr(g_pOptions->GetUnpackPassFile())) + if (!m_unpackOK && !m_unpackStartError && !m_unpackSpaceError && + (m_unpackDecryptError || m_unpackPasswordError) && + (!GetTerminated() || m_autoTerminated) && + Util::EmptyStr(m_password) && !Util::EmptyStr(g_pOptions->GetUnpackPassFile())) { FILE* infile = fopen(g_pOptions->GetUnpackPassFile(), FOPEN_RB); if (!infile) @@ -256,50 +256,50 @@ void UnpackController::UnpackArchives(EUnpacker eUnpacker, bool bMultiVolumes) return; } - char szPassword[512]; - while (!m_bUnpackOK && !m_bUnpackStartError && !m_bUnpackSpaceError && - (m_bUnpackDecryptError || m_bUnpackPasswordError) && - fgets(szPassword, sizeof(szPassword) - 1, infile)) + char password[512]; + while (!m_unpackOK && !m_unpackStartError && !m_unpackSpaceError && + (m_unpackDecryptError || m_unpackPasswordError) && + fgets(password, sizeof(password) - 1, infile)) { // trim trailing and - char* szEnd = szPassword + strlen(szPassword) - 1; - while (szEnd >= szPassword && (*szEnd == '\n' || *szEnd == '\r')) *szEnd-- = '\0'; + char* end = password + strlen(password) - 1; + while (end >= password && (*end == '\n' || *end == '\r')) *end-- = '\0'; - if (!Util::EmptyStr(szPassword)) + if (!Util::EmptyStr(password)) { - if (IsStopped() && m_bAutoTerminated) + if (IsStopped() && m_autoTerminated) { ScriptController::Resume(); Thread::Resume(); } - m_bUnpackDecryptError = false; - m_bUnpackPasswordError = false; - m_bAutoTerminated = false; - PrintMessage(Message::mkInfo, "Trying password %s for %s", szPassword, m_szName); - ExecuteUnpack(eUnpacker, szPassword, bMultiVolumes); + m_unpackDecryptError = false; + m_unpackPasswordError = false; + m_autoTerminated = false; + PrintMessage(Message::mkInfo, "Trying password %s for %s", password, m_name); + ExecuteUnpack(unpacker, password, multiVolumes); } } fclose(infile); - m_bPassListTried = !IsStopped() || m_bAutoTerminated; + m_passListTried = !IsStopped() || m_autoTerminated; } } -void UnpackController::ExecuteUnpack(EUnpacker eUnpacker, const char* szPassword, bool bMultiVolumes) +void UnpackController::ExecuteUnpack(EUnpacker unpacker, const char* password, bool multiVolumes) { - switch (eUnpacker) + switch (unpacker) { case upUnrar: - ExecuteUnrar(szPassword); + ExecuteUnrar(password); break; case upSevenZip: - ExecuteSevenZip(szPassword, bMultiVolumes); + ExecuteSevenZip(password, multiVolumes); break; } } -void UnpackController::ExecuteUnrar(const char* szPassword) +void UnpackController::ExecuteUnrar(const char* password) { // Format: // unrar x -y -p- -o+ *.rar ./_unpack/ @@ -317,12 +317,12 @@ void UnpackController::ExecuteUnrar(const char* szPassword) params.push_back(strdup("-y")); - if (!Util::EmptyStr(szPassword)) + if (!Util::EmptyStr(password)) { - char szPasswordParam[1024]; - snprintf(szPasswordParam, 1024, "-p%s", szPassword); - szPasswordParam[1024-1] = '\0'; - params.push_back(strdup(szPasswordParam)); + char passwordParam[1024]; + snprintf(passwordParam, 1024, "-p%s", password); + passwordParam[1024-1] = '\0'; + params.push_back(strdup(passwordParam)); } else { @@ -334,12 +334,12 @@ void UnpackController::ExecuteUnrar(const char* szPassword) params.push_back(strdup("-o+")); } - params.push_back(strdup(m_bHasNonStdRarFiles ? "*.*" : "*.rar")); + params.push_back(strdup(m_hasNonStdRarFiles ? "*.*" : "*.rar")); - char szUnpackDirParam[1024]; - snprintf(szUnpackDirParam, 1024, "%s%c", m_szUnpackDir, PATH_SEPARATOR); - szUnpackDirParam[1024-1] = '\0'; - params.push_back(strdup(szUnpackDirParam)); + char unpackDirParam[1024]; + snprintf(unpackDirParam, 1024, "%s%c", m_unpackDir, PATH_SEPARATOR); + unpackDirParam[1024-1] = '\0'; + params.push_back(strdup(unpackDirParam)); params.push_back(NULL); SetArgs((const char**)¶ms.front(), false); @@ -347,26 +347,26 @@ void UnpackController::ExecuteUnrar(const char* szPassword) SetLogPrefix("Unrar"); ResetEnv(); - m_bAllOKMessageReceived = false; - m_eUnpacker = upUnrar; + m_allOKMessageReceived = false; + m_unpacker = upUnrar; SetProgressLabel(""); - int iExitCode = Execute(); + int exitCode = Execute(); SetLogPrefix(NULL); SetProgressLabel(""); - m_bUnpackOK = iExitCode == 0 && m_bAllOKMessageReceived && !GetTerminated(); - m_bUnpackStartError = iExitCode == -1; - m_bUnpackSpaceError = iExitCode == 5; - m_bUnpackPasswordError |= iExitCode == 11; // only for rar5-archives + m_unpackOK = exitCode == 0 && m_allOKMessageReceived && !GetTerminated(); + m_unpackStartError = exitCode == -1; + m_unpackSpaceError = exitCode == 5; + m_unpackPasswordError |= exitCode == 11; // only for rar5-archives - if (!m_bUnpackOK && iExitCode > 0) + if (!m_unpackOK && exitCode > 0) { - PrintMessage(Message::mkError, "Unrar error code: %i", iExitCode); + PrintMessage(Message::mkError, "Unrar error code: %i", exitCode); } } -void UnpackController::ExecuteSevenZip(const char* szPassword, bool bMultiVolumes) +void UnpackController::ExecuteSevenZip(const char* password, bool multiVolumes) { // Format: // 7z x -y -p- -o./_unpack *.7z @@ -386,71 +386,71 @@ void UnpackController::ExecuteSevenZip(const char* szPassword, bool bMultiVolume params.push_back(strdup("-y")); - if (!Util::EmptyStr(szPassword)) + if (!Util::EmptyStr(password)) { - char szPasswordParam[1024]; - snprintf(szPasswordParam, 1024, "-p%s", szPassword); - szPasswordParam[1024-1] = '\0'; - params.push_back(strdup(szPasswordParam)); + char passwordParam[1024]; + snprintf(passwordParam, 1024, "-p%s", password); + passwordParam[1024-1] = '\0'; + params.push_back(strdup(passwordParam)); } else { params.push_back(strdup("-p-")); } - char szUnpackDirParam[1024]; - snprintf(szUnpackDirParam, 1024, "-o%s", m_szUnpackDir); - szUnpackDirParam[1024-1] = '\0'; - params.push_back(strdup(szUnpackDirParam)); + char unpackDirParam[1024]; + snprintf(unpackDirParam, 1024, "-o%s", m_unpackDir); + unpackDirParam[1024-1] = '\0'; + params.push_back(strdup(unpackDirParam)); - params.push_back(strdup(bMultiVolumes ? "*.7z.001" : "*.7z")); + params.push_back(strdup(multiVolumes ? "*.7z.001" : "*.7z")); params.push_back(NULL); SetArgs((const char**)¶ms.front(), false); SetScript(params.at(0)); ResetEnv(); - m_bAllOKMessageReceived = false; - m_eUnpacker = upSevenZip; + m_allOKMessageReceived = false; + m_unpacker = upSevenZip; PrintMessage(Message::mkInfo, "Executing 7-Zip"); SetLogPrefix("7-Zip"); SetProgressLabel(""); - int iExitCode = Execute(); + int exitCode = Execute(); SetLogPrefix(NULL); SetProgressLabel(""); - m_bUnpackOK = iExitCode == 0 && m_bAllOKMessageReceived && !GetTerminated(); - m_bUnpackStartError = iExitCode == -1; + m_unpackOK = exitCode == 0 && m_allOKMessageReceived && !GetTerminated(); + m_unpackStartError = exitCode == -1; - if (!m_bUnpackOK && iExitCode > 0) + if (!m_unpackOK && exitCode > 0) { - PrintMessage(Message::mkError, "7-Zip error code: %i", iExitCode); + PrintMessage(Message::mkError, "7-Zip error code: %i", exitCode); } } -bool UnpackController::PrepareCmdParams(const char* szCommand, ParamList* pParams, const char* szInfoName) +bool UnpackController::PrepareCmdParams(const char* command, ParamList* params, const char* infoName) { - if (Util::FileExists(szCommand)) + if (Util::FileExists(command)) { - pParams->push_back(strdup(szCommand)); + params->push_back(strdup(command)); return true; } - char** pCmdArgs = NULL; - if (!Util::SplitCommandLine(szCommand, &pCmdArgs)) + char** cmdArgs = NULL; + if (!Util::SplitCommandLine(command, &cmdArgs)) { - PrintMessage(Message::mkError, "Could not start %s, failed to parse command line: %s", szInfoName, szCommand); - m_bUnpackOK = false; - m_bUnpackStartError = true; + PrintMessage(Message::mkError, "Could not start %s, failed to parse command line: %s", infoName, command); + m_unpackOK = false; + m_unpackStartError = true; return false; } - for (char** szArgPtr = pCmdArgs; *szArgPtr; szArgPtr++) + for (char** argPtr = cmdArgs; *argPtr; argPtr++) { - pParams->push_back(*szArgPtr); + params->push_back(*argPtr); } - free(pCmdArgs); + free(cmdArgs); return true; } @@ -459,27 +459,27 @@ void UnpackController::JoinSplittedFiles() { SetLogPrefix("Join"); SetProgressLabel(""); - m_pPostInfo->SetStageProgress(0); + m_postInfo->SetStageProgress(0); // determine groups FileList groups; RegEx regExSplitExt(".*\\.[a-z,0-9]{3}\\.001$"); - DirBrowser dir(m_szDestDir); + DirBrowser dir(m_destDir); while (const char* filename = dir.Next()) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", m_szDestDir, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", m_destDir, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - if (strcmp(filename, ".") && strcmp(filename, "..") && !Util::DirectoryExists(szFullFilename)) + if (strcmp(filename, ".") && strcmp(filename, "..") && !Util::DirectoryExists(fullFilename)) { - if (regExSplitExt.Match(filename) && !FileHasRarSignature(szFullFilename)) + if (regExSplitExt.Match(filename) && !FileHasRarSignature(fullFilename)) { if (!JoinFile(filename)) { - m_bUnpackOK = false; + m_unpackOK = false; break; } } @@ -490,21 +490,21 @@ void UnpackController::JoinSplittedFiles() SetProgressLabel(""); } -bool UnpackController::JoinFile(const char* szFragBaseName) +bool UnpackController::JoinFile(const char* fragBaseName) { - char szDestBaseName[1024]; - strncpy(szDestBaseName, szFragBaseName, 1024); - szDestBaseName[1024-1] = '\0'; + char destBaseName[1024]; + strncpy(destBaseName, fragBaseName, 1024); + destBaseName[1024-1] = '\0'; // trim extension - char* szExtension = strrchr(szDestBaseName, '.'); - *szExtension = '\0'; + char* extension = strrchr(destBaseName, '.'); + *extension = '\0'; - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", m_szDestDir, PATH_SEPARATOR, szFragBaseName); - szFullFilename[1024-1] = '\0'; - long long lFirstSegmentSize = Util::FileSize(szFullFilename); - long long lDifSegmentSize = 0; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", m_destDir, PATH_SEPARATOR, fragBaseName); + fullFilename[1024-1] = '\0'; + long long firstSegmentSize = Util::FileSize(fullFilename); + long long difSegmentSize = 0; // Validate joinable file: // - fragments have continuous numbers (no holes); @@ -513,211 +513,211 @@ bool UnpackController::JoinFile(const char* szFragBaseName) // if it has the same size it is probably not the last and there are missing fragments. RegEx regExSplitExt(".*\\.[a-z,0-9]{3}\\.[0-9]{3}$"); - int iCount = 0; - int iMin = -1; - int iMax = -1; - int iDifSizeCount = 0; - int iDifSizeMin = 999999; - DirBrowser dir(m_szDestDir); + int count = 0; + int min = -1; + int max = -1; + int difSizeCount = 0; + int difSizeMin = 999999; + DirBrowser dir(m_destDir); while (const char* filename = dir.Next()) { - snprintf(szFullFilename, 1024, "%s%c%s", m_szDestDir, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + snprintf(fullFilename, 1024, "%s%c%s", m_destDir, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - if (strcmp(filename, ".") && strcmp(filename, "..") && !Util::DirectoryExists(szFullFilename) && + if (strcmp(filename, ".") && strcmp(filename, "..") && !Util::DirectoryExists(fullFilename) && regExSplitExt.Match(filename)) { - const char* szSegExt = strrchr(filename, '.'); - int iSegNum = atoi(szSegExt + 1); - iCount++; - iMin = iSegNum < iMin || iMin == -1 ? iSegNum : iMin; - iMax = iSegNum > iMax ? iSegNum : iMax; + const char* segExt = strrchr(filename, '.'); + int segNum = atoi(segExt + 1); + count++; + min = segNum < min || min == -1 ? segNum : min; + max = segNum > max ? segNum : max; - long long lSegmentSize = Util::FileSize(szFullFilename); - if (lSegmentSize != lFirstSegmentSize) + long long segmentSize = Util::FileSize(fullFilename); + if (segmentSize != firstSegmentSize) { - iDifSizeCount++; - iDifSizeMin = iSegNum < iDifSizeMin ? iSegNum : iDifSizeMin; - lDifSegmentSize = lSegmentSize; + difSizeCount++; + difSizeMin = segNum < difSizeMin ? segNum : difSizeMin; + difSegmentSize = segmentSize; } } } - int iCorrectedCount = iCount - (iMin == 0 ? 1 : 0); - if ((iMin > 1) || iCorrectedCount != iMax || - ((iDifSizeMin != iCorrectedCount || iDifSizeMin > iMax) && - m_pPostInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psSuccess)) + int correctedCount = count - (min == 0 ? 1 : 0); + if ((min > 1) || correctedCount != max || + ((difSizeMin != correctedCount || difSizeMin > max) && + m_postInfo->GetNZBInfo()->GetParStatus() != NZBInfo::psSuccess)) { - PrintMessage(Message::mkWarning, "Could not join splitted file %s: missing fragments detected", szDestBaseName); + PrintMessage(Message::mkWarning, "Could not join splitted file %s: missing fragments detected", destBaseName); return false; } // Now can join - PrintMessage(Message::mkInfo, "Joining splitted file %s", szDestBaseName); - m_pPostInfo->SetStageProgress(0); + PrintMessage(Message::mkInfo, "Joining splitted file %s", destBaseName); + m_postInfo->SetStageProgress(0); - char szErrBuf[256]; - char szDestFilename[1024]; - snprintf(szDestFilename, 1024, "%s%c%s", m_szUnpackDir, PATH_SEPARATOR, szDestBaseName); - szDestFilename[1024-1] = '\0'; + char errBuf[256]; + char destFilename[1024]; + snprintf(destFilename, 1024, "%s%c%s", m_unpackDir, PATH_SEPARATOR, destBaseName); + destFilename[1024-1] = '\0'; - FILE* pOutFile = fopen(szDestFilename, FOPEN_WBP); - if (!pOutFile) + FILE* outFile = fopen(destFilename, FOPEN_WBP); + if (!outFile) { - PrintMessage(Message::mkError, "Could not create file %s: %s", szDestFilename, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + PrintMessage(Message::mkError, "Could not create file %s: %s", destFilename, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); return false; } if (g_pOptions->GetWriteBuffer() > 0) { - setvbuf(pOutFile, NULL, _IOFBF, g_pOptions->GetWriteBuffer() * 1024); + setvbuf(outFile, NULL, _IOFBF, g_pOptions->GetWriteBuffer() * 1024); } - long long lTotalSize = lFirstSegmentSize * (iCount - 1) + lDifSegmentSize; - long long lWritten = 0; + long long totalSize = firstSegmentSize * (count - 1) + difSegmentSize; + long long written = 0; static const int BUFFER_SIZE = 1024 * 50; char* buffer = (char*)malloc(BUFFER_SIZE); - bool bOK = true; - for (int i = iMin; i <= iMax; i++) + bool ok = true; + for (int i = min; i <= max; i++) { - PrintMessage(Message::mkInfo, "Joining from %s.%.3i", szDestBaseName, i); + PrintMessage(Message::mkInfo, "Joining from %s.%.3i", destBaseName, i); - char szMessage[1024]; - snprintf(szMessage, 1024, "Joining from %s.%.3i", szDestBaseName, i); - szMessage[1024-1] = '\0'; - SetProgressLabel(szMessage); + char message[1024]; + snprintf(message, 1024, "Joining from %s.%.3i", destBaseName, i); + message[1024-1] = '\0'; + SetProgressLabel(message); - char szFragFilename[1024]; - snprintf(szFragFilename, 1024, "%s%c%s.%.3i", m_szDestDir, PATH_SEPARATOR, szDestBaseName, i); - szFragFilename[1024-1] = '\0'; - if (!Util::FileExists(szFragFilename)) + char fragFilename[1024]; + snprintf(fragFilename, 1024, "%s%c%s.%.3i", m_destDir, PATH_SEPARATOR, destBaseName, i); + fragFilename[1024-1] = '\0'; + if (!Util::FileExists(fragFilename)) { break; } - FILE* pInFile = fopen(szFragFilename, FOPEN_RB); - if (pInFile) + FILE* inFile = fopen(fragFilename, FOPEN_RB); + if (inFile) { int cnt = BUFFER_SIZE; while (cnt == BUFFER_SIZE) { - cnt = (int)fread(buffer, 1, BUFFER_SIZE, pInFile); - fwrite(buffer, 1, cnt, pOutFile); - lWritten += cnt; - m_pPostInfo->SetStageProgress(int(lWritten * 1000 / lTotalSize)); + cnt = (int)fread(buffer, 1, BUFFER_SIZE, inFile); + fwrite(buffer, 1, cnt, outFile); + written += cnt; + m_postInfo->SetStageProgress(int(written * 1000 / totalSize)); } - fclose(pInFile); + fclose(inFile); - char szFragFilename[1024]; - snprintf(szFragFilename, 1024, "%s.%.3i", szDestBaseName, i); - szFragFilename[1024-1] = '\0'; - m_JoinedFiles.push_back(strdup(szFragFilename)); + char fragFilename[1024]; + snprintf(fragFilename, 1024, "%s.%.3i", destBaseName, i); + fragFilename[1024-1] = '\0'; + m_joinedFiles.push_back(strdup(fragFilename)); } else { - PrintMessage(Message::mkError, "Could not open file %s", szFragFilename); - bOK = false; + PrintMessage(Message::mkError, "Could not open file %s", fragFilename); + ok = false; break; } } - fclose(pOutFile); + fclose(outFile); free(buffer); - return bOK; + return ok; } void UnpackController::Completed() { - bool bCleanupSuccess = Cleanup(); + bool cleanupSuccess = Cleanup(); - if (m_bUnpackOK && bCleanupSuccess) + if (m_unpackOK && cleanupSuccess) { - PrintMessage(Message::mkInfo, "%s %s", m_szInfoNameUp, "successful"); - m_pPostInfo->GetNZBInfo()->SetUnpackStatus(NZBInfo::usSuccess); - m_pPostInfo->GetNZBInfo()->SetUnpackCleanedUpDisk(m_bCleanedUpDisk); + PrintMessage(Message::mkInfo, "%s %s", m_infoNameUp, "successful"); + m_postInfo->GetNZBInfo()->SetUnpackStatus(NZBInfo::usSuccess); + m_postInfo->GetNZBInfo()->SetUnpackCleanedUpDisk(m_cleanedUpDisk); if (g_pOptions->GetParRename()) { //request par-rename check for extracted files - m_pPostInfo->GetNZBInfo()->SetRenameStatus(NZBInfo::rsNone); + m_postInfo->GetNZBInfo()->SetRenameStatus(NZBInfo::rsNone); } - m_pPostInfo->SetStage(PostInfo::ptQueued); + m_postInfo->SetStage(PostInfo::ptQueued); } else { #ifndef DISABLE_PARCHECK - if (!m_bUnpackOK && - (m_pPostInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped || - !m_pPostInfo->GetNZBInfo()->GetParFull()) && - !m_bUnpackStartError && !m_bUnpackSpaceError && !m_bUnpackPasswordError && - (!GetTerminated() || m_bAutoTerminated) && m_bHasParFiles) + if (!m_unpackOK && + (m_postInfo->GetNZBInfo()->GetParStatus() <= NZBInfo::psSkipped || + !m_postInfo->GetNZBInfo()->GetParFull()) && + !m_unpackStartError && !m_unpackSpaceError && !m_unpackPasswordError && + (!GetTerminated() || m_autoTerminated) && m_hasParFiles) { - RequestParCheck(!Util::EmptyStr(m_szPassword) || - Util::EmptyStr(g_pOptions->GetUnpackPassFile()) || m_bPassListTried || - !(m_bUnpackDecryptError || m_bUnpackPasswordError) || - m_pPostInfo->GetNZBInfo()->GetParStatus() > NZBInfo::psSkipped); + RequestParCheck(!Util::EmptyStr(m_password) || + Util::EmptyStr(g_pOptions->GetUnpackPassFile()) || m_passListTried || + !(m_unpackDecryptError || m_unpackPasswordError) || + m_postInfo->GetNZBInfo()->GetParStatus() > NZBInfo::psSkipped); } else #endif { - PrintMessage(Message::mkError, "%s failed", m_szInfoNameUp); - m_pPostInfo->GetNZBInfo()->SetUnpackStatus( - m_bUnpackSpaceError ? NZBInfo::usSpace : - m_bUnpackPasswordError || m_bUnpackDecryptError ? NZBInfo::usPassword : + PrintMessage(Message::mkError, "%s failed", m_infoNameUp); + m_postInfo->GetNZBInfo()->SetUnpackStatus( + m_unpackSpaceError ? NZBInfo::usSpace : + m_unpackPasswordError || m_unpackDecryptError ? NZBInfo::usPassword : NZBInfo::usFailure); - m_pPostInfo->SetStage(PostInfo::ptQueued); + m_postInfo->SetStage(PostInfo::ptQueued); } } } #ifndef DISABLE_PARCHECK -void UnpackController::RequestParCheck(bool bForceRepair) +void UnpackController::RequestParCheck(bool forceRepair) { - PrintMessage(Message::mkInfo, "%s requested %s", m_szInfoNameUp, bForceRepair ? "par-check with forced repair" : "par-check/repair"); - m_pPostInfo->SetRequestParCheck(true); - m_pPostInfo->SetForceRepair(bForceRepair); - m_pPostInfo->SetStage(PostInfo::ptFinished); - m_pPostInfo->SetUnpackTried(true); - m_pPostInfo->SetPassListTried(m_bPassListTried); - m_pPostInfo->SetLastUnpackStatus((int)(m_bUnpackSpaceError ? NZBInfo::usSpace : - m_bUnpackPasswordError || m_bUnpackDecryptError ? NZBInfo::usPassword : + PrintMessage(Message::mkInfo, "%s requested %s", m_infoNameUp, forceRepair ? "par-check with forced repair" : "par-check/repair"); + m_postInfo->SetRequestParCheck(true); + m_postInfo->SetForceRepair(forceRepair); + m_postInfo->SetStage(PostInfo::ptFinished); + m_postInfo->SetUnpackTried(true); + m_postInfo->SetPassListTried(m_passListTried); + m_postInfo->SetLastUnpackStatus((int)(m_unpackSpaceError ? NZBInfo::usSpace : + m_unpackPasswordError || m_unpackDecryptError ? NZBInfo::usPassword : NZBInfo::usFailure)); } #endif void UnpackController::CreateUnpackDir() { - m_bInterDir = strlen(g_pOptions->GetInterDir()) > 0 && - !strncmp(m_szDestDir, g_pOptions->GetInterDir(), strlen(g_pOptions->GetInterDir())); - if (m_bInterDir) + m_interDir = strlen(g_pOptions->GetInterDir()) > 0 && + !strncmp(m_destDir, g_pOptions->GetInterDir(), strlen(g_pOptions->GetInterDir())); + if (m_interDir) { - m_pPostInfo->GetNZBInfo()->BuildFinalDirName(m_szFinalDir, 1024); - m_szFinalDir[1024-1] = '\0'; - snprintf(m_szUnpackDir, 1024, "%s%c%s", m_szFinalDir, PATH_SEPARATOR, "_unpack"); - m_bFinalDirCreated = !Util::DirectoryExists(m_szFinalDir); + m_postInfo->GetNZBInfo()->BuildFinalDirName(m_finalDir, 1024); + m_finalDir[1024-1] = '\0'; + snprintf(m_unpackDir, 1024, "%s%c%s", m_finalDir, PATH_SEPARATOR, "_unpack"); + m_finalDirCreated = !Util::DirectoryExists(m_finalDir); } else { - snprintf(m_szUnpackDir, 1024, "%s%c%s", m_szDestDir, PATH_SEPARATOR, "_unpack"); + snprintf(m_unpackDir, 1024, "%s%c%s", m_destDir, PATH_SEPARATOR, "_unpack"); } - m_szUnpackDir[1024-1] = '\0'; + m_unpackDir[1024-1] = '\0'; - char szErrBuf[1024]; - if (!Util::ForceDirectories(m_szUnpackDir, szErrBuf, sizeof(szErrBuf))) + char errBuf[1024]; + if (!Util::ForceDirectories(m_unpackDir, errBuf, sizeof(errBuf))) { - PrintMessage(Message::mkError, "Could not create directory %s: %s", m_szUnpackDir, szErrBuf); + PrintMessage(Message::mkError, "Could not create directory %s: %s", m_unpackDir, errBuf); } } -void UnpackController::CheckArchiveFiles(bool bScanNonStdFiles) +void UnpackController::CheckArchiveFiles(bool scanNonStdFiles) { - m_bHasRarFiles = false; - m_bHasNonStdRarFiles = false; - m_bHasSevenZipFiles = false; - m_bHasSevenZipMultiFiles = false; - m_bHasSplittedFiles = false; + m_hasRarFiles = false; + m_hasNonStdRarFiles = false; + m_hasSevenZipFiles = false; + m_hasSevenZipMultiFiles = false; + m_hasSplittedFiles = false; RegEx regExRar(".*\\.rar$"); RegEx regExRarMultiSeq(".*\\.(r|s)[0-9][0-9]$"); @@ -726,45 +726,45 @@ void UnpackController::CheckArchiveFiles(bool bScanNonStdFiles) RegEx regExNumExt(".*\\.[0-9]+$"); RegEx regExSplitExt(".*\\.[a-z,0-9]{3}\\.[0-9]{3}$"); - DirBrowser dir(m_szDestDir); + DirBrowser dir(m_destDir); while (const char* filename = dir.Next()) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", m_szDestDir, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", m_destDir, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - if (strcmp(filename, ".") && strcmp(filename, "..") && !Util::DirectoryExists(szFullFilename)) + if (strcmp(filename, ".") && strcmp(filename, "..") && !Util::DirectoryExists(fullFilename)) { - const char* szExt = strchr(filename, '.'); - int iExtNum = szExt ? atoi(szExt + 1) : -1; + const char* ext = strchr(filename, '.'); + int extNum = ext ? atoi(ext + 1) : -1; if (regExRar.Match(filename)) { - m_bHasRarFiles = true; + m_hasRarFiles = true; } else if (regExSevenZip.Match(filename)) { - m_bHasSevenZipFiles = true; + m_hasSevenZipFiles = true; } else if (regExSevenZipMulti.Match(filename)) { - m_bHasSevenZipMultiFiles = true; + m_hasSevenZipMultiFiles = true; } - else if (bScanNonStdFiles && !m_bHasNonStdRarFiles && iExtNum > 1 && + else if (scanNonStdFiles && !m_hasNonStdRarFiles && extNum > 1 && !regExRarMultiSeq.Match(filename) && regExNumExt.Match(filename) && - FileHasRarSignature(szFullFilename)) + FileHasRarSignature(fullFilename)) { - m_bHasNonStdRarFiles = true; + m_hasNonStdRarFiles = true; } - else if (regExSplitExt.Match(filename) && (iExtNum == 0 || iExtNum == 1)) + else if (regExSplitExt.Match(filename) && (extNum == 0 || extNum == 1)) { - m_bHasSplittedFiles = true; + m_hasSplittedFiles = true; } } } } -bool UnpackController::FileHasRarSignature(const char* szFilename) +bool UnpackController::FileHasRarSignature(const char* filename) { char rar4Signature[] = { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00 }; char rar5Signature[] = { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x01, 0x00 }; @@ -773,16 +773,16 @@ bool UnpackController::FileHasRarSignature(const char* szFilename) int cnt = 0; FILE* infile; - infile = fopen(szFilename, FOPEN_RB); + infile = fopen(filename, FOPEN_RB); if (infile) { cnt = (int)fread(fileSignature, 1, sizeof(fileSignature), infile); fclose(infile); } - bool bRar = cnt == sizeof(fileSignature) && + bool rar = cnt == sizeof(fileSignature) && (!strcmp(rar4Signature, fileSignature) || !strcmp(rar5Signature, fileSignature)); - return bRar; + return rar; } bool UnpackController::Cleanup() @@ -794,37 +794,37 @@ bool UnpackController::Cleanup() // By failure: // - remove _unpack-dir. - bool bOK = true; + bool ok = true; FileList extractedFiles; - if (m_bUnpackOK) + if (m_unpackOK) { // moving files back - DirBrowser dir(m_szUnpackDir); + DirBrowser dir(m_unpackDir); while (const char* filename = dir.Next()) { if (strcmp(filename, ".") && strcmp(filename, "..")) { - char szSrcFile[1024]; - snprintf(szSrcFile, 1024, "%s%c%s", m_szUnpackDir, PATH_SEPARATOR, filename); - szSrcFile[1024-1] = '\0'; + char srcFile[1024]; + snprintf(srcFile, 1024, "%s%c%s", m_unpackDir, PATH_SEPARATOR, filename); + srcFile[1024-1] = '\0'; - char szDstFile[1024]; - snprintf(szDstFile, 1024, "%s%c%s", m_szFinalDir[0] != '\0' ? m_szFinalDir : m_szDestDir, PATH_SEPARATOR, filename); - szDstFile[1024-1] = '\0'; + char dstFile[1024]; + snprintf(dstFile, 1024, "%s%c%s", m_finalDir[0] != '\0' ? m_finalDir : m_destDir, PATH_SEPARATOR, filename); + dstFile[1024-1] = '\0'; // silently overwrite existing files - remove(szDstFile); + remove(dstFile); - bool bHiddenFile = filename[0] == '.'; + bool hiddenFile = filename[0] == '.'; - if (!Util::MoveFile(szSrcFile, szDstFile) && !bHiddenFile) + if (!Util::MoveFile(srcFile, dstFile) && !hiddenFile) { - char szErrBuf[256]; - PrintMessage(Message::mkError, "Could not move file %s to %s: %s", szSrcFile, szDstFile, - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); - bOK = false; + char errBuf[256]; + PrintMessage(Message::mkError, "Could not move file %s to %s: %s", srcFile, dstFile, + Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); + ok = false; } extractedFiles.push_back(strdup(filename)); @@ -832,18 +832,18 @@ bool UnpackController::Cleanup() } } - char szErrBuf[256]; - if (bOK && !Util::DeleteDirectoryWithContent(m_szUnpackDir, szErrBuf, sizeof(szErrBuf))) + char errBuf[256]; + if (ok && !Util::DeleteDirectoryWithContent(m_unpackDir, errBuf, sizeof(errBuf))) { - PrintMessage(Message::mkError, "Could not delete temporary directory %s: %s", m_szUnpackDir, szErrBuf); + PrintMessage(Message::mkError, "Could not delete temporary directory %s: %s", m_unpackDir, errBuf); } - if (!m_bUnpackOK && m_bFinalDirCreated) + if (!m_unpackOK && m_finalDirCreated) { - Util::RemoveDirectory(m_szFinalDir); + Util::RemoveDirectory(m_finalDir); } - if (m_bUnpackOK && bOK && g_pOptions->GetUnpackCleanupDisk()) + if (m_unpackOK && ok && g_pOptions->GetUnpackCleanupDisk()) { PrintMessage(Message::mkInfo, "Deleting archive files"); @@ -853,37 +853,37 @@ bool UnpackController::Cleanup() RegEx regExNumExt(".*\\.[0-9]+$"); RegEx regExSplitExt(".*\\.[a-z,0-9]{3}\\.[0-9]{3}$"); - DirBrowser dir(m_szDestDir); + DirBrowser dir(m_destDir); while (const char* filename = dir.Next()) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", m_szDestDir, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", m_destDir, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; if (strcmp(filename, ".") && strcmp(filename, "..") && - !Util::DirectoryExists(szFullFilename) && - (m_bInterDir || !extractedFiles.Exists(filename)) && + !Util::DirectoryExists(fullFilename) && + (m_interDir || !extractedFiles.Exists(filename)) && (regExRar.Match(filename) || regExSevenZip.Match(filename) || - (regExRarMultiSeq.Match(filename) && FileHasRarSignature(szFullFilename)) || - (m_bHasNonStdRarFiles && regExNumExt.Match(filename) && FileHasRarSignature(szFullFilename)) || - (m_bHasSplittedFiles && regExSplitExt.Match(filename) && m_JoinedFiles.Exists(filename)))) + (regExRarMultiSeq.Match(filename) && FileHasRarSignature(fullFilename)) || + (m_hasNonStdRarFiles && regExNumExt.Match(filename) && FileHasRarSignature(fullFilename)) || + (m_hasSplittedFiles && regExSplitExt.Match(filename) && m_joinedFiles.Exists(filename)))) { PrintMessage(Message::mkInfo, "Deleting file %s", filename); - if (remove(szFullFilename) != 0) + if (remove(fullFilename) != 0) { - char szErrBuf[256]; - PrintMessage(Message::mkError, "Could not delete file %s: %s", szFullFilename, Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf))); + char errBuf[256]; + PrintMessage(Message::mkError, "Could not delete file %s: %s", fullFilename, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } } - m_bCleanedUpDisk = true; + m_cleanedUpDisk = true; } extractedFiles.Clear(); - return bOK; + return ok; } /** @@ -891,17 +891,17 @@ bool UnpackController::Cleanup() * In order to print progress continuously we analyze the output after every char * and update post-job progress information. */ -bool UnpackController::ReadLine(char* szBuf, int iBufSize, FILE* pStream) +bool UnpackController::ReadLine(char* buf, int bufSize, FILE* stream) { - bool bPrinted = false; + bool printed = false; int i = 0; - for (; i < iBufSize - 1; i++) + for (; i < bufSize - 1; i++) { - int ch = fgetc(pStream); - szBuf[i] = ch; - szBuf[i+1] = '\0'; + int ch = fgetc(stream); + buf[i] = ch; + buf[i+1] = '\0'; if (ch == EOF) { break; @@ -912,118 +912,118 @@ bool UnpackController::ReadLine(char* szBuf, int iBufSize, FILE* pStream) break; } - char* szBackspace = strrchr(szBuf, '\b'); - if (szBackspace) + char* backspace = strrchr(buf, '\b'); + if (backspace) { - if (!bPrinted) + if (!printed) { char tmp[1024]; - strncpy(tmp, szBuf, 1024); + strncpy(tmp, buf, 1024); tmp[1024-1] = '\0'; - char* szTmpPercent = strrchr(tmp, '\b'); - if (szTmpPercent) + char* tmpPercent = strrchr(tmp, '\b'); + if (tmpPercent) { - *szTmpPercent = '\0'; + *tmpPercent = '\0'; } - if (strncmp(szBuf, "...", 3)) + if (strncmp(buf, "...", 3)) { ProcessOutput(tmp); } - bPrinted = true; + printed = true; } - if (strchr(szBackspace, '%')) + if (strchr(backspace, '%')) { - int iPercent = atoi(szBackspace + 1); - m_pPostInfo->SetStageProgress(iPercent * 10); + int percent = atoi(backspace + 1); + m_postInfo->SetStageProgress(percent * 10); } } } - szBuf[i] = '\0'; + buf[i] = '\0'; - if (bPrinted) + if (printed) { - szBuf[0] = '\0'; + buf[0] = '\0'; } return i > 0; } -void UnpackController::AddMessage(Message::EKind eKind, const char* szText) +void UnpackController::AddMessage(Message::EKind kind, const char* text) { - char szMsgText[1024]; - strncpy(szMsgText, szText, 1024); - szMsgText[1024-1] = '\0'; - int iLen = strlen(szText); + char msgText[1024]; + strncpy(msgText, text, 1024); + msgText[1024-1] = '\0'; + int len = strlen(text); // Modify unrar messages for better readability: // remove the destination path part from message "Extracting file.xxx" - if (m_eUnpacker == upUnrar && !strncmp(szText, "Unrar: Extracting ", 19) && - !strncmp(szText + 19, m_szUnpackDir, strlen(m_szUnpackDir))) + if (m_unpacker == upUnrar && !strncmp(text, "Unrar: Extracting ", 19) && + !strncmp(text + 19, m_unpackDir, strlen(m_unpackDir))) { - snprintf(szMsgText, 1024, "Unrar: Extracting %s", szText + 19 + strlen(m_szUnpackDir) + 1); - szMsgText[1024-1] = '\0'; + snprintf(msgText, 1024, "Unrar: Extracting %s", text + 19 + strlen(m_unpackDir) + 1); + msgText[1024-1] = '\0'; } - m_pPostInfo->GetNZBInfo()->AddMessage(eKind, szMsgText); + m_postInfo->GetNZBInfo()->AddMessage(kind, msgText); - if (m_eUnpacker == upUnrar && !strncmp(szMsgText, "Unrar: UNRAR ", 6) && - strstr(szMsgText, " Copyright ") && strstr(szMsgText, " Alexander Roshal")) + if (m_unpacker == upUnrar && !strncmp(msgText, "Unrar: UNRAR ", 6) && + strstr(msgText, " Copyright ") && strstr(msgText, " Alexander Roshal")) { // reset start time for a case if user uses unpack-script to do some things // (like sending Wake-On-Lan message) before executing unrar - m_pPostInfo->SetStageTime(time(NULL)); + m_postInfo->SetStageTime(time(NULL)); } - if (m_eUnpacker == upUnrar && !strncmp(szMsgText, "Unrar: Extracting ", 18)) + if (m_unpacker == upUnrar && !strncmp(msgText, "Unrar: Extracting ", 18)) { - SetProgressLabel(szMsgText + 7); + SetProgressLabel(msgText + 7); } - if (m_eUnpacker == upUnrar && !strncmp(szText, "Unrar: Extracting from ", 23)) + if (m_unpacker == upUnrar && !strncmp(text, "Unrar: Extracting from ", 23)) { - const char *szFilename = szText + 23; - debug("Filename: %s", szFilename); - SetProgressLabel(szText + 7); + const char *filename = text + 23; + debug("Filename: %s", filename); + SetProgressLabel(text + 7); } - if (m_eUnpacker == upUnrar && - (!strncmp(szText, "Unrar: Checksum error in the encrypted file", 42) || - !strncmp(szText, "Unrar: CRC failed in the encrypted file", 39))) + if (m_unpacker == upUnrar && + (!strncmp(text, "Unrar: Checksum error in the encrypted file", 42) || + !strncmp(text, "Unrar: CRC failed in the encrypted file", 39))) { - m_bUnpackDecryptError = true; + m_unpackDecryptError = true; } - if (m_eUnpacker == upUnrar && !strncmp(szText, "Unrar: The specified password is incorrect.'", 43)) + if (m_unpacker == upUnrar && !strncmp(text, "Unrar: The specified password is incorrect.'", 43)) { - m_bUnpackPasswordError = true; + m_unpackPasswordError = true; } - if (m_eUnpacker == upSevenZip && - (iLen > 18 && !strncmp(szText + iLen - 45, "Data Error in encrypted file. Wrong password?", 45))) + if (m_unpacker == upSevenZip && + (len > 18 && !strncmp(text + len - 45, "Data Error in encrypted file. Wrong password?", 45))) { - m_bUnpackDecryptError = true; + m_unpackDecryptError = true; } - if (!IsStopped() && (m_bUnpackDecryptError || m_bUnpackPasswordError || - strstr(szText, " : packed data CRC failed in volume") || - strstr(szText, " : packed data checksum error in volume") || - (iLen > 13 && !strncmp(szText + iLen - 13, " - CRC failed", 13)) || - (iLen > 18 && !strncmp(szText + iLen - 18, " - checksum failed", 18)) || - !strncmp(szText, "Unrar: WARNING: You need to start extraction from a previous volume", 67))) + if (!IsStopped() && (m_unpackDecryptError || m_unpackPasswordError || + strstr(text, " : packed data CRC failed in volume") || + strstr(text, " : packed data checksum error in volume") || + (len > 13 && !strncmp(text + len - 13, " - CRC failed", 13)) || + (len > 18 && !strncmp(text + len - 18, " - checksum failed", 18)) || + !strncmp(text, "Unrar: WARNING: You need to start extraction from a previous volume", 67))) { - char szMsgText[1024]; - snprintf(szMsgText, 1024, "Cancelling %s due to errors", m_szInfoName); - szMsgText[1024-1] = '\0'; - m_pPostInfo->GetNZBInfo()->AddMessage(Message::mkWarning, szMsgText); - m_bAutoTerminated = true; + char msgText[1024]; + snprintf(msgText, 1024, "Cancelling %s due to errors", m_infoName); + msgText[1024-1] = '\0'; + m_postInfo->GetNZBInfo()->AddMessage(Message::mkWarning, msgText); + m_autoTerminated = true; Stop(); } - if ((m_eUnpacker == upUnrar && !strncmp(szText, "Unrar: All OK", 13)) || - (m_eUnpacker == upSevenZip && !strncmp(szText, "7-Zip: Everything is Ok", 23))) + if ((m_unpacker == upUnrar && !strncmp(text, "Unrar: All OK", 13)) || + (m_unpacker == upSevenZip && !strncmp(text, "7-Zip: Everything is Ok", 23))) { - m_bAllOKMessageReceived = true; + m_allOKMessageReceived = true; } } @@ -1034,9 +1034,9 @@ void UnpackController::Stop() Terminate(); } -void UnpackController::SetProgressLabel(const char* szProgressLabel) +void UnpackController::SetProgressLabel(const char* progressLabel) { DownloadQueue::Lock(); - m_pPostInfo->SetProgressLabel(szProgressLabel); + m_postInfo->SetProgressLabel(progressLabel); DownloadQueue::Unlock(); } diff --git a/daemon/postprocess/Unpack.h b/daemon/postprocess/Unpack.h index 656b95fa..1473b905 100644 --- a/daemon/postprocess/Unpack.h +++ b/daemon/postprocess/Unpack.h @@ -48,7 +48,7 @@ private: { public: void Clear(); - bool Exists(const char* szFilename); + bool Exists(const char* filename); }; typedef std::vector ParamListBase; @@ -56,63 +56,63 @@ private: { public: ~ParamList(); - bool Exists(const char* szParam); + bool Exists(const char* param); }; private: - PostInfo* m_pPostInfo; - char m_szName[1024]; - char m_szInfoName[1024]; - char m_szInfoNameUp[1024]; - char m_szDestDir[1024]; - char m_szFinalDir[1024]; - char m_szUnpackDir[1024]; - char m_szPassword[1024]; - bool m_bInterDir; - bool m_bAllOKMessageReceived; - bool m_bNoFilesMessageReceived; - bool m_bHasParFiles; - bool m_bHasRarFiles; - bool m_bHasNonStdRarFiles; - bool m_bHasSevenZipFiles; - bool m_bHasSevenZipMultiFiles; - bool m_bHasSplittedFiles; - bool m_bUnpackOK; - bool m_bUnpackStartError; - bool m_bUnpackSpaceError; - bool m_bUnpackDecryptError; - bool m_bUnpackPasswordError; - bool m_bCleanedUpDisk; - bool m_bAutoTerminated; - EUnpacker m_eUnpacker; - bool m_bFinalDirCreated; - FileList m_JoinedFiles; - bool m_bPassListTried; + PostInfo* m_postInfo; + char m_name[1024]; + char m_infoName[1024]; + char m_infoNameUp[1024]; + char m_destDir[1024]; + char m_finalDir[1024]; + char m_unpackDir[1024]; + char m_password[1024]; + bool m_interDir; + bool m_allOKMessageReceived; + bool m_noFilesMessageReceived; + bool m_hasParFiles; + bool m_hasRarFiles; + bool m_hasNonStdRarFiles; + bool m_hasSevenZipFiles; + bool m_hasSevenZipMultiFiles; + bool m_hasSplittedFiles; + bool m_unpackOK; + bool m_unpackStartError; + bool m_unpackSpaceError; + bool m_unpackDecryptError; + bool m_unpackPasswordError; + bool m_cleanedUpDisk; + bool m_autoTerminated; + EUnpacker m_unpacker; + bool m_finalDirCreated; + FileList m_joinedFiles; + bool m_passListTried; protected: - virtual bool ReadLine(char* szBuf, int iBufSize, FILE* pStream); - virtual void AddMessage(Message::EKind eKind, const char* szText); - void ExecuteUnpack(EUnpacker eUnpacker, const char* szPassword, bool bMultiVolumes); - void ExecuteUnrar(const char* szPassword); - void ExecuteSevenZip(const char* szPassword, bool bMultiVolumes); - void UnpackArchives(EUnpacker eUnpacker, bool bMultiVolumes); + virtual bool ReadLine(char* buf, int bufSize, FILE* stream); + virtual void AddMessage(Message::EKind kind, const char* text); + void ExecuteUnpack(EUnpacker unpacker, const char* password, bool multiVolumes); + void ExecuteUnrar(const char* password); + void ExecuteSevenZip(const char* password, bool multiVolumes); + void UnpackArchives(EUnpacker unpacker, bool multiVolumes); void JoinSplittedFiles(); - bool JoinFile(const char* szFragBaseName); + bool JoinFile(const char* fragBaseName); void Completed(); void CreateUnpackDir(); bool Cleanup(); - void CheckArchiveFiles(bool bScanNonStdFiles); - void SetProgressLabel(const char* szProgressLabel); + void CheckArchiveFiles(bool scanNonStdFiles); + void SetProgressLabel(const char* progressLabel); #ifndef DISABLE_PARCHECK - void RequestParCheck(bool bForceRepair); + void RequestParCheck(bool forceRepair); #endif - bool FileHasRarSignature(const char* szFilename); - bool PrepareCmdParams(const char* szCommand, ParamList* pParams, const char* szInfoName); + bool FileHasRarSignature(const char* filename); + bool PrepareCmdParams(const char* command, ParamList* params, const char* infoName); public: virtual void Run(); virtual void Stop(); - static void StartJob(PostInfo* pPostInfo); + static void StartJob(PostInfo* postInfo); }; #endif diff --git a/daemon/queue/DiskState.cpp b/daemon/queue/DiskState.cpp index e603e2c0..11e635c2 100644 --- a/daemon/queue/DiskState.cpp +++ b/daemon/queue/DiskState.cpp @@ -69,122 +69,122 @@ int vsscanf(const char *s, const char *fmt, va_list ap) /* Parse signature and return format version number */ -int ParseFormatVersion(const char* szFormatSignature) +int ParseFormatVersion(const char* formatSignature) { - if (strncmp(szFormatSignature, FORMATVERSION_SIGNATURE, strlen(FORMATVERSION_SIGNATURE))) + if (strncmp(formatSignature, FORMATVERSION_SIGNATURE, strlen(FORMATVERSION_SIGNATURE))) { return 0; } - return atoi(szFormatSignature + strlen(FORMATVERSION_SIGNATURE)); + return atoi(formatSignature + strlen(FORMATVERSION_SIGNATURE)); } class StateFile { private: - char m_szDestFilename[1024]; - char m_szTempFilename[1024]; - int m_iFormatVersion; - int m_iFileVersion; - FILE* m_pFile; + char m_destFilename[1024]; + char m_tempFilename[1024]; + int m_formatVersion; + int m_fileVersion; + FILE* m_file; public: - StateFile(const char* szFilename, int iFormatVersion); + StateFile(const char* filename, int formatVersion); ~StateFile(); void Discard(); bool FileExists(); FILE* BeginWriteTransaction(); bool FinishWriteTransaction(); FILE* BeginReadTransaction(); - int GetFileVersion() { return m_iFileVersion; } - const char* GetDestFilename() { return m_szDestFilename; } + int GetFileVersion() { return m_fileVersion; } + const char* GetDestFilename() { return m_destFilename; } }; -StateFile::StateFile(const char* szFilename, int iFormatVersion) +StateFile::StateFile(const char* filename, int formatVersion) { - m_pFile = NULL; + m_file = NULL; - m_iFormatVersion = iFormatVersion; + m_formatVersion = formatVersion; - snprintf(m_szDestFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), szFilename); - m_szDestFilename[1024-1] = '\0'; + snprintf(m_destFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), filename); + m_destFilename[1024-1] = '\0'; - snprintf(m_szTempFilename, 1024, "%s%s.new", g_pOptions->GetQueueDir(), szFilename); - m_szTempFilename[1024-1] = '\0'; + snprintf(m_tempFilename, 1024, "%s%s.new", g_pOptions->GetQueueDir(), filename); + m_tempFilename[1024-1] = '\0'; } StateFile::~StateFile() { - if (m_pFile) + if (m_file) { - fclose(m_pFile); + fclose(m_file); } } void StateFile::Discard() { - remove(m_szDestFilename); + remove(m_destFilename); } bool StateFile::FileExists() { - return Util::FileExists(m_szDestFilename) || Util::FileExists(m_szTempFilename); + return Util::FileExists(m_destFilename) || Util::FileExists(m_tempFilename); } FILE* StateFile::BeginWriteTransaction() { - m_pFile = fopen(m_szTempFilename, FOPEN_WB); + m_file = fopen(m_tempFilename, FOPEN_WB); - if (!m_pFile) + if (!m_file) { - char szErrBuf[256]; - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf)); - error("Error saving diskstate: Could not create file %s: %s", m_szTempFilename, szErrBuf); + char errBuf[256]; + Util::GetLastErrorMessage(errBuf, sizeof(errBuf)); + error("Error saving diskstate: Could not create file %s: %s", m_tempFilename, errBuf); return NULL; } - fprintf(m_pFile, "%s%i\n", FORMATVERSION_SIGNATURE, m_iFormatVersion); + fprintf(m_file, "%s%i\n", FORMATVERSION_SIGNATURE, m_formatVersion); - return m_pFile; + return m_file; } bool StateFile::FinishWriteTransaction() { - char szErrBuf[256]; + char errBuf[256]; // flush file content before renaming if (g_pOptions->GetFlushQueue()) { - debug("Flushing data for file %s", Util::BaseFileName(m_szTempFilename)); - fflush(m_pFile); - if (!Util::FlushFileBuffers(fileno(m_pFile), szErrBuf, sizeof(szErrBuf))) + debug("Flushing data for file %s", Util::BaseFileName(m_tempFilename)); + fflush(m_file); + if (!Util::FlushFileBuffers(fileno(m_file), errBuf, sizeof(errBuf))) { - warn("Could not flush file %s into disk: %s", m_szTempFilename, szErrBuf); + warn("Could not flush file %s into disk: %s", m_tempFilename, errBuf); } } - fclose(m_pFile); - m_pFile = NULL; + fclose(m_file); + m_file = NULL; // now rename to dest file name - remove(m_szDestFilename); - if (rename(m_szTempFilename, m_szDestFilename)) + remove(m_destFilename); + if (rename(m_tempFilename, m_destFilename)) { - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf)); + Util::GetLastErrorMessage(errBuf, sizeof(errBuf)); error("Error saving diskstate: Could not rename file %s to %s: %s", - m_szTempFilename, m_szDestFilename, szErrBuf); + m_tempFilename, m_destFilename, errBuf); return false; } // flush directory buffer after renaming if (g_pOptions->GetFlushQueue()) { - debug("Flushing directory for file %s", Util::BaseFileName(m_szDestFilename)); - if (!Util::FlushDirBuffers(m_szDestFilename, szErrBuf, sizeof(szErrBuf))) + debug("Flushing directory for file %s", Util::BaseFileName(m_destFilename)); + if (!Util::FlushDirBuffers(m_destFilename, errBuf, sizeof(errBuf))) { - warn("Could not flush directory buffers for file %s into disk: %s", m_szDestFilename, szErrBuf); + warn("Could not flush directory buffers for file %s into disk: %s", m_destFilename, errBuf); } } @@ -193,42 +193,42 @@ bool StateFile::FinishWriteTransaction() FILE* StateFile::BeginReadTransaction() { - if (!Util::FileExists(m_szDestFilename) && Util::FileExists(m_szTempFilename)) + if (!Util::FileExists(m_destFilename) && Util::FileExists(m_tempFilename)) { // disaster recovery: temp-file exists but the dest-file doesn't - warn("Restoring diskstate file %s from %s", Util::BaseFileName(m_szDestFilename), Util::BaseFileName(m_szTempFilename)); - if (rename(m_szTempFilename, m_szDestFilename)) + warn("Restoring diskstate file %s from %s", Util::BaseFileName(m_destFilename), Util::BaseFileName(m_tempFilename)); + if (rename(m_tempFilename, m_destFilename)) { - char szErrBuf[256]; - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf)); + char errBuf[256]; + Util::GetLastErrorMessage(errBuf, sizeof(errBuf)); error("Error restoring diskstate: Could not rename file %s to %s: %s", - m_szTempFilename, m_szDestFilename, szErrBuf); + m_tempFilename, m_destFilename, errBuf); return NULL; } } - m_pFile = fopen(m_szDestFilename, FOPEN_RB); + m_file = fopen(m_destFilename, FOPEN_RB); - if (!m_pFile) + if (!m_file) { - char szErrBuf[256]; - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf)); - error("Error reading diskstate: could not open file %s: %s", m_szDestFilename, szErrBuf); + char errBuf[256]; + Util::GetLastErrorMessage(errBuf, sizeof(errBuf)); + error("Error reading diskstate: could not open file %s: %s", m_destFilename, errBuf); return NULL; } char FileSignatur[128]; - fgets(FileSignatur, sizeof(FileSignatur), m_pFile); - m_iFileVersion = ParseFormatVersion(FileSignatur); - if (m_iFileVersion > m_iFormatVersion) + fgets(FileSignatur, sizeof(FileSignatur), m_file); + m_fileVersion = ParseFormatVersion(FileSignatur); + if (m_fileVersion > m_formatVersion) { error("Could not load diskstate due to file version mismatch"); - fclose(m_pFile); - m_pFile = NULL; + fclose(m_file); + m_file = NULL; return NULL; } - return m_pFile; + return m_file; } /* @@ -237,15 +237,15 @@ FILE* StateFile::BeginReadTransaction() */ int DiskState::fscanf(FILE* infile, const char* Format, ...) { - char szLine[1024]; - if (!fgets(szLine, sizeof(szLine), infile)) + char line[1024]; + if (!fgets(line, sizeof(line), infile)) { return 0; } va_list ap; va_start(ap, Format); - int res = vsscanf(szLine, Format, ap); + int res = vsscanf(line, Format, ap); va_end(ap); return res; @@ -262,14 +262,14 @@ int DiskState::fscanf(FILE* infile, const char* Format, ...) * - then delete queue * - then rename queue.new to queue */ -bool DiskState::SaveDownloadQueue(DownloadQueue* pDownloadQueue) +bool DiskState::SaveDownloadQueue(DownloadQueue* downloadQueue) { debug("Saving queue to disk"); StateFile stateFile("queue", 55); - if (pDownloadQueue->GetQueue()->empty() && - pDownloadQueue->GetHistory()->empty()) + if (downloadQueue->GetQueue()->empty() && + downloadQueue->GetHistory()->empty()) { stateFile.Discard(); return true; @@ -282,16 +282,16 @@ bool DiskState::SaveDownloadQueue(DownloadQueue* pDownloadQueue) } // save nzb-infos - SaveNZBQueue(pDownloadQueue, outfile); + SaveNZBQueue(downloadQueue, outfile); // save history - SaveHistory(pDownloadQueue, outfile); + SaveHistory(downloadQueue, outfile); // now rename to dest file name return stateFile.FinishWriteTransaction(); } -bool DiskState::LoadDownloadQueue(DownloadQueue* pDownloadQueue, Servers* pServers) +bool DiskState::LoadDownloadQueue(DownloadQueue* downloadQueue, Servers* servers) { debug("Loading queue from disk"); @@ -303,77 +303,77 @@ bool DiskState::LoadDownloadQueue(DownloadQueue* pDownloadQueue, Servers* pServe return false; } - bool bOK = false; - int iFormatVersion = stateFile.GetFileVersion(); + bool ok = false; + int formatVersion = stateFile.GetFileVersion(); NZBList nzbList(false); NZBList sortList(false); - if (iFormatVersion < 43) + if (formatVersion < 43) { // load nzb-infos - if (!LoadNZBList(&nzbList, pServers, infile, iFormatVersion)) goto error; + if (!LoadNZBList(&nzbList, servers, infile, formatVersion)) goto error; // load file-infos - if (!LoadFileQueue12(&nzbList, &sortList, infile, iFormatVersion)) goto error; + if (!LoadFileQueue12(&nzbList, &sortList, infile, formatVersion)) goto error; } else { - if (!LoadNZBList(pDownloadQueue->GetQueue(), pServers, infile, iFormatVersion)) goto error; + if (!LoadNZBList(downloadQueue->GetQueue(), servers, infile, formatVersion)) goto error; } - if (iFormatVersion >= 7 && iFormatVersion < 45) + if (formatVersion >= 7 && formatVersion < 45) { // load post-queue from v12 - if (!LoadPostQueue12(pDownloadQueue, &nzbList, infile, iFormatVersion)) goto error; + if (!LoadPostQueue12(downloadQueue, &nzbList, infile, formatVersion)) goto error; } - else if (iFormatVersion < 7) + else if (formatVersion < 7) { // load post-queue from v5 - LoadPostQueue5(pDownloadQueue, &nzbList); + LoadPostQueue5(downloadQueue, &nzbList); } - if (iFormatVersion >= 15 && iFormatVersion < 46) + if (formatVersion >= 15 && formatVersion < 46) { // load url-queue - if (!LoadUrlQueue12(pDownloadQueue, infile, iFormatVersion)) goto error; + if (!LoadUrlQueue12(downloadQueue, infile, formatVersion)) goto error; } - if (iFormatVersion >= 9) + if (formatVersion >= 9) { // load history - if (!LoadHistory(pDownloadQueue, &nzbList, pServers, infile, iFormatVersion)) goto error; + if (!LoadHistory(downloadQueue, &nzbList, servers, infile, formatVersion)) goto error; } - if (iFormatVersion >= 9 && iFormatVersion < 43) + if (formatVersion >= 9 && formatVersion < 43) { // load parked file-infos - if (!LoadFileQueue12(&nzbList, NULL, infile, iFormatVersion)) goto error; + if (!LoadFileQueue12(&nzbList, NULL, infile, formatVersion)) goto error; } - if (iFormatVersion < 29) + if (formatVersion < 29) { CalcCriticalHealth(&nzbList); } - if (iFormatVersion < 43) + if (formatVersion < 43) { // finalize queue reading - CompleteNZBList12(pDownloadQueue, &sortList, iFormatVersion); + CompleteNZBList12(downloadQueue, &sortList, formatVersion); } - if (iFormatVersion < 47) + if (formatVersion < 47) { - CompleteDupList12(pDownloadQueue, iFormatVersion); + CompleteDupList12(downloadQueue, formatVersion); } - if (!LoadAllFileStates(pDownloadQueue, pServers)) goto error; + if (!LoadAllFileStates(downloadQueue, servers)) goto error; - bOK = true; + ok = true; error: - if (!bOK) + if (!ok) { error("Error reading diskstate for download queue and history"); } @@ -381,66 +381,66 @@ error: NZBInfo::ResetGenID(true); FileInfo::ResetGenID(true); - if (iFormatVersion > 0) + if (formatVersion > 0) { - CalcFileStats(pDownloadQueue, iFormatVersion); + CalcFileStats(downloadQueue, formatVersion); } - return bOK; + return ok; } -void DiskState::CompleteNZBList12(DownloadQueue* pDownloadQueue, NZBList* pNZBList, int iFormatVersion) +void DiskState::CompleteNZBList12(DownloadQueue* downloadQueue, NZBList* nzbList, int formatVersion) { // put all NZBs referenced from file queue into pDownloadQueue->GetQueue() - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo = *it; - pDownloadQueue->GetQueue()->push_back(pNZBInfo); + NZBInfo* nzbInfo = *it; + downloadQueue->GetQueue()->push_back(nzbInfo); } - if (31 <= iFormatVersion && iFormatVersion < 42) + if (31 <= formatVersion && formatVersion < 42) { // due to a bug in r811 (v12-testing) new NZBIDs were generated on each refresh of web-ui // this resulted in very high numbers for NZBIDs // here we renumber NZBIDs in order to keep them low. NZBInfo::ResetGenID(false); - int iID = 1; - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + int id = 1; + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo = *it; - pNZBInfo->SetID(iID++); + NZBInfo* nzbInfo = *it; + nzbInfo->SetID(id++); } } } -void DiskState::CompleteDupList12(DownloadQueue* pDownloadQueue, int iFormatVersion) +void DiskState::CompleteDupList12(DownloadQueue* downloadQueue, int formatVersion) { NZBInfo::ResetGenID(true); - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; + HistoryInfo* historyInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkDup) + if (historyInfo->GetKind() == HistoryInfo::hkDup) { - pHistoryInfo->GetDupInfo()->SetID(NZBInfo::GenerateID()); + historyInfo->GetDupInfo()->SetID(NZBInfo::GenerateID()); } } } -void DiskState::SaveNZBQueue(DownloadQueue* pDownloadQueue, FILE* outfile) +void DiskState::SaveNZBQueue(DownloadQueue* downloadQueue, FILE* outfile) { debug("Saving nzb list to disk"); - fprintf(outfile, "%i\n", (int)pDownloadQueue->GetQueue()->size()); - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + fprintf(outfile, "%i\n", (int)downloadQueue->GetQueue()->size()); + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - SaveNZBInfo(pNZBInfo, outfile); + NZBInfo* nzbInfo = *it; + SaveNZBInfo(nzbInfo, outfile); } } -bool DiskState::LoadNZBList(NZBList* pNZBList, Servers* pServers, FILE* infile, int iFormatVersion) +bool DiskState::LoadNZBList(NZBList* nzbList, Servers* servers, FILE* infile, int formatVersion) { debug("Loading nzb list from disk"); @@ -449,9 +449,9 @@ bool DiskState::LoadNZBList(NZBList* pNZBList, Servers* pServers, FILE* infile, if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - NZBInfo* pNZBInfo = new NZBInfo(); - pNZBList->push_back(pNZBInfo); - if (!LoadNZBInfo(pNZBInfo, pServers, infile, iFormatVersion)) goto error; + NZBInfo* nzbInfo = new NZBInfo(); + nzbList->push_back(nzbInfo); + if (!LoadNZBInfo(nzbInfo, servers, infile, formatVersion)) goto error; } return true; @@ -461,588 +461,588 @@ error: return false; } -void DiskState::SaveNZBInfo(NZBInfo* pNZBInfo, FILE* outfile) +void DiskState::SaveNZBInfo(NZBInfo* nzbInfo, FILE* outfile) { - fprintf(outfile, "%i\n", pNZBInfo->GetID()); - fprintf(outfile, "%i\n", (int)pNZBInfo->GetKind()); - fprintf(outfile, "%s\n", pNZBInfo->GetURL()); - fprintf(outfile, "%s\n", pNZBInfo->GetFilename()); - fprintf(outfile, "%s\n", pNZBInfo->GetDestDir()); - fprintf(outfile, "%s\n", pNZBInfo->GetFinalDir()); - fprintf(outfile, "%s\n", pNZBInfo->GetQueuedFilename()); - fprintf(outfile, "%s\n", pNZBInfo->GetName()); - fprintf(outfile, "%s\n", pNZBInfo->GetCategory()); - fprintf(outfile, "%i,%i,%i,%i,%i\n", (int)pNZBInfo->GetPriority(), - pNZBInfo->GetPostInfo() ? (int)pNZBInfo->GetPostInfo()->GetStage() + 1 : 0, - (int)pNZBInfo->GetDeletePaused(), (int)pNZBInfo->GetManyDupeFiles(), pNZBInfo->GetFeedID()); - fprintf(outfile, "%i,%i,%i,%i,%i,%i,%i\n", (int)pNZBInfo->GetParStatus(), (int)pNZBInfo->GetUnpackStatus(), - (int)pNZBInfo->GetMoveStatus(), (int)pNZBInfo->GetRenameStatus(), (int)pNZBInfo->GetDeleteStatus(), - (int)pNZBInfo->GetMarkStatus(), (int)pNZBInfo->GetUrlStatus()); - fprintf(outfile, "%i,%i,%i\n", (int)pNZBInfo->GetUnpackCleanedUpDisk(), (int)pNZBInfo->GetHealthPaused(), - (int)pNZBInfo->GetAddUrlPaused()); - fprintf(outfile, "%i,%i,%i\n", pNZBInfo->GetFileCount(), pNZBInfo->GetParkedFileCount(), - pNZBInfo->GetMessageCount()); - fprintf(outfile, "%i,%i\n", (int)pNZBInfo->GetMinTime(), (int)pNZBInfo->GetMaxTime()); - fprintf(outfile, "%i,%i,%i,%i\n", (int)pNZBInfo->GetParFull(), - pNZBInfo->GetPostInfo() ? (int)pNZBInfo->GetPostInfo()->GetForceParFull() : 0, - pNZBInfo->GetPostInfo() ? (int)pNZBInfo->GetPostInfo()->GetForceRepair() : 0, - pNZBInfo->GetExtraParBlocks()); + fprintf(outfile, "%i\n", nzbInfo->GetID()); + fprintf(outfile, "%i\n", (int)nzbInfo->GetKind()); + fprintf(outfile, "%s\n", nzbInfo->GetURL()); + fprintf(outfile, "%s\n", nzbInfo->GetFilename()); + fprintf(outfile, "%s\n", nzbInfo->GetDestDir()); + fprintf(outfile, "%s\n", nzbInfo->GetFinalDir()); + fprintf(outfile, "%s\n", nzbInfo->GetQueuedFilename()); + fprintf(outfile, "%s\n", nzbInfo->GetName()); + fprintf(outfile, "%s\n", nzbInfo->GetCategory()); + fprintf(outfile, "%i,%i,%i,%i,%i\n", (int)nzbInfo->GetPriority(), + nzbInfo->GetPostInfo() ? (int)nzbInfo->GetPostInfo()->GetStage() + 1 : 0, + (int)nzbInfo->GetDeletePaused(), (int)nzbInfo->GetManyDupeFiles(), nzbInfo->GetFeedID()); + fprintf(outfile, "%i,%i,%i,%i,%i,%i,%i\n", (int)nzbInfo->GetParStatus(), (int)nzbInfo->GetUnpackStatus(), + (int)nzbInfo->GetMoveStatus(), (int)nzbInfo->GetRenameStatus(), (int)nzbInfo->GetDeleteStatus(), + (int)nzbInfo->GetMarkStatus(), (int)nzbInfo->GetUrlStatus()); + fprintf(outfile, "%i,%i,%i\n", (int)nzbInfo->GetUnpackCleanedUpDisk(), (int)nzbInfo->GetHealthPaused(), + (int)nzbInfo->GetAddUrlPaused()); + fprintf(outfile, "%i,%i,%i\n", nzbInfo->GetFileCount(), nzbInfo->GetParkedFileCount(), + nzbInfo->GetMessageCount()); + fprintf(outfile, "%i,%i\n", (int)nzbInfo->GetMinTime(), (int)nzbInfo->GetMaxTime()); + fprintf(outfile, "%i,%i,%i,%i\n", (int)nzbInfo->GetParFull(), + nzbInfo->GetPostInfo() ? (int)nzbInfo->GetPostInfo()->GetForceParFull() : 0, + nzbInfo->GetPostInfo() ? (int)nzbInfo->GetPostInfo()->GetForceRepair() : 0, + nzbInfo->GetExtraParBlocks()); - fprintf(outfile, "%u,%u\n", pNZBInfo->GetFullContentHash(), pNZBInfo->GetFilteredContentHash()); + fprintf(outfile, "%u,%u\n", nzbInfo->GetFullContentHash(), nzbInfo->GetFilteredContentHash()); unsigned long High1, Low1, High2, Low2, High3, Low3; - Util::SplitInt64(pNZBInfo->GetSize(), &High1, &Low1); - Util::SplitInt64(pNZBInfo->GetSuccessSize(), &High2, &Low2); - Util::SplitInt64(pNZBInfo->GetFailedSize(), &High3, &Low3); + Util::SplitInt64(nzbInfo->GetSize(), &High1, &Low1); + Util::SplitInt64(nzbInfo->GetSuccessSize(), &High2, &Low2); + Util::SplitInt64(nzbInfo->GetFailedSize(), &High3, &Low3); fprintf(outfile, "%lu,%lu,%lu,%lu,%lu,%lu\n", High1, Low1, High2, Low2, High3, Low3); - Util::SplitInt64(pNZBInfo->GetParSize(), &High1, &Low1); - Util::SplitInt64(pNZBInfo->GetParSuccessSize(), &High2, &Low2); - Util::SplitInt64(pNZBInfo->GetParFailedSize(), &High3, &Low3); + Util::SplitInt64(nzbInfo->GetParSize(), &High1, &Low1); + Util::SplitInt64(nzbInfo->GetParSuccessSize(), &High2, &Low2); + Util::SplitInt64(nzbInfo->GetParFailedSize(), &High3, &Low3); fprintf(outfile, "%lu,%lu,%lu,%lu,%lu,%lu\n", High1, Low1, High2, Low2, High3, Low3); - fprintf(outfile, "%i,%i,%i\n", pNZBInfo->GetTotalArticles(), pNZBInfo->GetSuccessArticles(), pNZBInfo->GetFailedArticles()); + fprintf(outfile, "%i,%i,%i\n", nzbInfo->GetTotalArticles(), nzbInfo->GetSuccessArticles(), nzbInfo->GetFailedArticles()); - fprintf(outfile, "%s\n", pNZBInfo->GetDupeKey()); - fprintf(outfile, "%i,%i\n", (int)pNZBInfo->GetDupeMode(), pNZBInfo->GetDupeScore()); + fprintf(outfile, "%s\n", nzbInfo->GetDupeKey()); + fprintf(outfile, "%i,%i\n", (int)nzbInfo->GetDupeMode(), nzbInfo->GetDupeScore()); - Util::SplitInt64(pNZBInfo->GetDownloadedSize(), &High1, &Low1); - fprintf(outfile, "%lu,%lu,%i,%i,%i,%i,%i\n", High1, Low1, pNZBInfo->GetDownloadSec(), pNZBInfo->GetPostTotalSec(), - pNZBInfo->GetParSec(), pNZBInfo->GetRepairSec(), pNZBInfo->GetUnpackSec()); + Util::SplitInt64(nzbInfo->GetDownloadedSize(), &High1, &Low1); + fprintf(outfile, "%lu,%lu,%i,%i,%i,%i,%i\n", High1, Low1, nzbInfo->GetDownloadSec(), nzbInfo->GetPostTotalSec(), + nzbInfo->GetParSec(), nzbInfo->GetRepairSec(), nzbInfo->GetUnpackSec()); - fprintf(outfile, "%i\n", (int)pNZBInfo->GetCompletedFiles()->size()); - for (CompletedFiles::iterator it = pNZBInfo->GetCompletedFiles()->begin(); it != pNZBInfo->GetCompletedFiles()->end(); it++) + fprintf(outfile, "%i\n", (int)nzbInfo->GetCompletedFiles()->size()); + for (CompletedFiles::iterator it = nzbInfo->GetCompletedFiles()->begin(); it != nzbInfo->GetCompletedFiles()->end(); it++) { - CompletedFile* pCompletedFile = *it; - fprintf(outfile, "%i,%i,%lu,%s\n", pCompletedFile->GetID(), (int)pCompletedFile->GetStatus(), - pCompletedFile->GetCrc(), pCompletedFile->GetFileName()); + CompletedFile* completedFile = *it; + fprintf(outfile, "%i,%i,%lu,%s\n", completedFile->GetID(), (int)completedFile->GetStatus(), + completedFile->GetCrc(), completedFile->GetFileName()); } - fprintf(outfile, "%i\n", (int)pNZBInfo->GetParameters()->size()); - for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++) + fprintf(outfile, "%i\n", (int)nzbInfo->GetParameters()->size()); + for (NZBParameterList::iterator it = nzbInfo->GetParameters()->begin(); it != nzbInfo->GetParameters()->end(); it++) { - NZBParameter* pParameter = *it; - fprintf(outfile, "%s=%s\n", pParameter->GetName(), pParameter->GetValue()); + NZBParameter* parameter = *it; + fprintf(outfile, "%s=%s\n", parameter->GetName(), parameter->GetValue()); } - fprintf(outfile, "%i\n", (int)pNZBInfo->GetScriptStatuses()->size()); - for (ScriptStatusList::iterator it = pNZBInfo->GetScriptStatuses()->begin(); it != pNZBInfo->GetScriptStatuses()->end(); it++) + fprintf(outfile, "%i\n", (int)nzbInfo->GetScriptStatuses()->size()); + for (ScriptStatusList::iterator it = nzbInfo->GetScriptStatuses()->begin(); it != nzbInfo->GetScriptStatuses()->end(); it++) { - ScriptStatus* pScriptStatus = *it; - fprintf(outfile, "%i,%s\n", pScriptStatus->GetStatus(), pScriptStatus->GetName()); + ScriptStatus* scriptStatus = *it; + fprintf(outfile, "%i,%s\n", scriptStatus->GetStatus(), scriptStatus->GetName()); } - SaveServerStats(pNZBInfo->GetServerStats(), outfile); + SaveServerStats(nzbInfo->GetServerStats(), outfile); // save file-infos - int iSize = 0; - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + int size = 0; + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - if (!pFileInfo->GetDeleted()) + FileInfo* fileInfo = *it; + if (!fileInfo->GetDeleted()) { - iSize++; + size++; } } - fprintf(outfile, "%i\n", iSize); - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + fprintf(outfile, "%i\n", size); + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - if (!pFileInfo->GetDeleted()) + FileInfo* fileInfo = *it; + if (!fileInfo->GetDeleted()) { - fprintf(outfile, "%i,%i,%i,%i\n", pFileInfo->GetID(), (int)pFileInfo->GetPaused(), - (int)pFileInfo->GetTime(), (int)pFileInfo->GetExtraPriority()); + fprintf(outfile, "%i,%i,%i,%i\n", fileInfo->GetID(), (int)fileInfo->GetPaused(), + (int)fileInfo->GetTime(), (int)fileInfo->GetExtraPriority()); } } } -bool DiskState::LoadNZBInfo(NZBInfo* pNZBInfo, Servers* pServers, FILE* infile, int iFormatVersion) +bool DiskState::LoadNZBInfo(NZBInfo* nzbInfo, Servers* servers, FILE* infile, int formatVersion) { char buf[10240]; - if (iFormatVersion >= 24) + if (formatVersion >= 24) { - int iID; - if (fscanf(infile, "%i\n", &iID) != 1) goto error; - pNZBInfo->SetID(iID); + int id; + if (fscanf(infile, "%i\n", &id) != 1) goto error; + nzbInfo->SetID(id); } - if (iFormatVersion >= 46) + if (formatVersion >= 46) { - int iKind; - if (fscanf(infile, "%i\n", &iKind) != 1) goto error; - pNZBInfo->SetKind((NZBInfo::EKind)iKind); + int kind; + if (fscanf(infile, "%i\n", &kind) != 1) goto error; + nzbInfo->SetKind((NZBInfo::EKind)kind); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetURL(buf); + nzbInfo->SetURL(buf); } if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetFilename(buf); + nzbInfo->SetFilename(buf); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetDestDir(buf); + nzbInfo->SetDestDir(buf); - if (iFormatVersion >= 27) + if (formatVersion >= 27) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetFinalDir(buf); + nzbInfo->SetFinalDir(buf); } - if (iFormatVersion >= 5) + if (formatVersion >= 5) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetQueuedFilename(buf); + nzbInfo->SetQueuedFilename(buf); } - if (iFormatVersion >= 13) + if (formatVersion >= 13) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' if (strlen(buf) > 0) { - pNZBInfo->SetName(buf); + nzbInfo->SetName(buf); } } - if (iFormatVersion >= 4) + if (formatVersion >= 4) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetCategory(buf); + nzbInfo->SetCategory(buf); } if (true) // clang requires a block for goto to work { - int iPriority = 0, iPostProcess = 0, iPostStage = 0, iDeletePaused = 0, iManyDupeFiles = 0, iFeedID = 0; - if (iFormatVersion >= 54) + int priority = 0, postProcess = 0, postStage = 0, deletePaused = 0, manyDupeFiles = 0, feedId = 0; + if (formatVersion >= 54) { - if (fscanf(infile, "%i,%i,%i,%i,%i\n", &iPriority, &iPostStage, &iDeletePaused, &iManyDupeFiles, &iFeedID) != 5) goto error; + if (fscanf(infile, "%i,%i,%i,%i,%i\n", &priority, &postStage, &deletePaused, &manyDupeFiles, &feedId) != 5) goto error; } - else if (iFormatVersion >= 45) + else if (formatVersion >= 45) { - if (fscanf(infile, "%i,%i,%i,%i\n", &iPriority, &iPostStage, &iDeletePaused, &iManyDupeFiles) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &priority, &postStage, &deletePaused, &manyDupeFiles) != 4) goto error; } - else if (iFormatVersion >= 44) + else if (formatVersion >= 44) { - if (fscanf(infile, "%i,%i,%i,%i\n", &iPriority, &iPostProcess, &iDeletePaused, &iManyDupeFiles) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &priority, &postProcess, &deletePaused, &manyDupeFiles) != 4) goto error; } - else if (iFormatVersion >= 41) + else if (formatVersion >= 41) { - if (fscanf(infile, "%i,%i,%i\n", &iPostProcess, &iDeletePaused, &iManyDupeFiles) != 3) goto error; + if (fscanf(infile, "%i,%i,%i\n", &postProcess, &deletePaused, &manyDupeFiles) != 3) goto error; } - else if (iFormatVersion >= 40) + else if (formatVersion >= 40) { - if (fscanf(infile, "%i,%i\n", &iPostProcess, &iDeletePaused) != 2) goto error; + if (fscanf(infile, "%i,%i\n", &postProcess, &deletePaused) != 2) goto error; } - else if (iFormatVersion >= 4) + else if (formatVersion >= 4) { - if (fscanf(infile, "%i\n", &iPostProcess) != 1) goto error; + if (fscanf(infile, "%i\n", &postProcess) != 1) goto error; } - pNZBInfo->SetPriority(iPriority); - pNZBInfo->SetDeletePaused((bool)iDeletePaused); - pNZBInfo->SetManyDupeFiles((bool)iManyDupeFiles); - if (iPostStage > 0) + nzbInfo->SetPriority(priority); + nzbInfo->SetDeletePaused((bool)deletePaused); + nzbInfo->SetManyDupeFiles((bool)manyDupeFiles); + if (postStage > 0) { - pNZBInfo->EnterPostProcess(); - pNZBInfo->GetPostInfo()->SetStage((PostInfo::EStage)iPostStage); + nzbInfo->EnterPostProcess(); + nzbInfo->GetPostInfo()->SetStage((PostInfo::EStage)postStage); } - pNZBInfo->SetFeedID(iFeedID); + nzbInfo->SetFeedID(feedId); } - if (iFormatVersion >= 8 && iFormatVersion < 18) + if (formatVersion >= 8 && formatVersion < 18) { - int iParStatus; - if (fscanf(infile, "%i\n", &iParStatus) != 1) goto error; - pNZBInfo->SetParStatus((NZBInfo::EParStatus)iParStatus); + int parStatus; + if (fscanf(infile, "%i\n", &parStatus) != 1) goto error; + nzbInfo->SetParStatus((NZBInfo::EParStatus)parStatus); } - if (iFormatVersion >= 9 && iFormatVersion < 18) + if (formatVersion >= 9 && formatVersion < 18) { - int iScriptStatus; - if (fscanf(infile, "%i\n", &iScriptStatus) != 1) goto error; - if (iScriptStatus > 1) iScriptStatus--; - pNZBInfo->GetScriptStatuses()->Add("SCRIPT", (ScriptStatus::EStatus)iScriptStatus); + int scriptStatus; + if (fscanf(infile, "%i\n", &scriptStatus) != 1) goto error; + if (scriptStatus > 1) scriptStatus--; + nzbInfo->GetScriptStatuses()->Add("SCRIPT", (ScriptStatus::EStatus)scriptStatus); } - if (iFormatVersion >= 18) + if (formatVersion >= 18) { - int iParStatus, iUnpackStatus, iScriptStatus, iMoveStatus = 0, iRenameStatus = 0, - iDeleteStatus = 0, iMarkStatus = 0, iUrlStatus = 0; - if (iFormatVersion >= 46) + int parStatus, unpackStatus, scriptStatus, moveStatus = 0, renameStatus = 0, + deleteStatus = 0, markStatus = 0, urlStatus = 0; + if (formatVersion >= 46) { - if (fscanf(infile, "%i,%i,%i,%i,%i,%i,%i\n", &iParStatus, &iUnpackStatus, &iMoveStatus, - &iRenameStatus, &iDeleteStatus, &iMarkStatus, &iUrlStatus) != 7) goto error; + if (fscanf(infile, "%i,%i,%i,%i,%i,%i,%i\n", &parStatus, &unpackStatus, &moveStatus, + &renameStatus, &deleteStatus, &markStatus, &urlStatus) != 7) goto error; } - else if (iFormatVersion >= 37) + else if (formatVersion >= 37) { - if (fscanf(infile, "%i,%i,%i,%i,%i,%i\n", &iParStatus, &iUnpackStatus, - &iMoveStatus, &iRenameStatus, &iDeleteStatus, &iMarkStatus) != 6) goto error; + if (fscanf(infile, "%i,%i,%i,%i,%i,%i\n", &parStatus, &unpackStatus, + &moveStatus, &renameStatus, &deleteStatus, &markStatus) != 6) goto error; } - else if (iFormatVersion >= 35) + else if (formatVersion >= 35) { - if (fscanf(infile, "%i,%i,%i,%i,%i\n", &iParStatus, &iUnpackStatus, - &iMoveStatus, &iRenameStatus, &iDeleteStatus) != 5) goto error; + if (fscanf(infile, "%i,%i,%i,%i,%i\n", &parStatus, &unpackStatus, + &moveStatus, &renameStatus, &deleteStatus) != 5) goto error; } - else if (iFormatVersion >= 23) + else if (formatVersion >= 23) { - if (fscanf(infile, "%i,%i,%i,%i\n", &iParStatus, &iUnpackStatus, - &iMoveStatus, &iRenameStatus) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &parStatus, &unpackStatus, + &moveStatus, &renameStatus) != 4) goto error; } - else if (iFormatVersion >= 21) + else if (formatVersion >= 21) { - if (fscanf(infile, "%i,%i,%i,%i,%i\n", &iParStatus, &iUnpackStatus, - &iScriptStatus, &iMoveStatus, &iRenameStatus) != 5) goto error; + if (fscanf(infile, "%i,%i,%i,%i,%i\n", &parStatus, &unpackStatus, + &scriptStatus, &moveStatus, &renameStatus) != 5) goto error; } - else if (iFormatVersion >= 20) + else if (formatVersion >= 20) { - if (fscanf(infile, "%i,%i,%i,%i\n", &iParStatus, &iUnpackStatus, - &iScriptStatus, &iMoveStatus) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &parStatus, &unpackStatus, + &scriptStatus, &moveStatus) != 4) goto error; } else { - if (fscanf(infile, "%i,%i,%i\n", &iParStatus, &iUnpackStatus, &iScriptStatus) != 3) goto error; + if (fscanf(infile, "%i,%i,%i\n", &parStatus, &unpackStatus, &scriptStatus) != 3) goto error; } - pNZBInfo->SetParStatus((NZBInfo::EParStatus)iParStatus); - pNZBInfo->SetUnpackStatus((NZBInfo::EUnpackStatus)iUnpackStatus); - pNZBInfo->SetMoveStatus((NZBInfo::EMoveStatus)iMoveStatus); - pNZBInfo->SetRenameStatus((NZBInfo::ERenameStatus)iRenameStatus); - pNZBInfo->SetDeleteStatus((NZBInfo::EDeleteStatus)iDeleteStatus); - pNZBInfo->SetMarkStatus((NZBInfo::EMarkStatus)iMarkStatus); - if (pNZBInfo->GetKind() == NZBInfo::nkNzb || - (NZBInfo::EUrlStatus)iUrlStatus >= NZBInfo::lsFailed || - (NZBInfo::EUrlStatus)iUrlStatus >= NZBInfo::lsScanSkipped) + nzbInfo->SetParStatus((NZBInfo::EParStatus)parStatus); + nzbInfo->SetUnpackStatus((NZBInfo::EUnpackStatus)unpackStatus); + nzbInfo->SetMoveStatus((NZBInfo::EMoveStatus)moveStatus); + nzbInfo->SetRenameStatus((NZBInfo::ERenameStatus)renameStatus); + nzbInfo->SetDeleteStatus((NZBInfo::EDeleteStatus)deleteStatus); + nzbInfo->SetMarkStatus((NZBInfo::EMarkStatus)markStatus); + if (nzbInfo->GetKind() == NZBInfo::nkNzb || + (NZBInfo::EUrlStatus)urlStatus >= NZBInfo::lsFailed || + (NZBInfo::EUrlStatus)urlStatus >= NZBInfo::lsScanSkipped) { - pNZBInfo->SetUrlStatus((NZBInfo::EUrlStatus)iUrlStatus); + nzbInfo->SetUrlStatus((NZBInfo::EUrlStatus)urlStatus); } - if (iFormatVersion < 23) + if (formatVersion < 23) { - if (iScriptStatus > 1) iScriptStatus--; - pNZBInfo->GetScriptStatuses()->Add("SCRIPT", (ScriptStatus::EStatus)iScriptStatus); + if (scriptStatus > 1) scriptStatus--; + nzbInfo->GetScriptStatuses()->Add("SCRIPT", (ScriptStatus::EStatus)scriptStatus); } } - if (iFormatVersion >= 35) + if (formatVersion >= 35) { - int iUnpackCleanedUpDisk, iHealthPaused, iAddUrlPaused = 0; - if (iFormatVersion >= 46) + int unpackCleanedUpDisk, healthPaused, addUrlPaused = 0; + if (formatVersion >= 46) { - if (fscanf(infile, "%i,%i,%i\n", &iUnpackCleanedUpDisk, &iHealthPaused, &iAddUrlPaused) != 3) goto error; + if (fscanf(infile, "%i,%i,%i\n", &unpackCleanedUpDisk, &healthPaused, &addUrlPaused) != 3) goto error; } else { - if (fscanf(infile, "%i,%i\n", &iUnpackCleanedUpDisk, &iHealthPaused) != 2) goto error; + if (fscanf(infile, "%i,%i\n", &unpackCleanedUpDisk, &healthPaused) != 2) goto error; } - pNZBInfo->SetUnpackCleanedUpDisk((bool)iUnpackCleanedUpDisk); - pNZBInfo->SetHealthPaused((bool)iHealthPaused); - pNZBInfo->SetAddUrlPaused((bool)iAddUrlPaused); + nzbInfo->SetUnpackCleanedUpDisk((bool)unpackCleanedUpDisk); + nzbInfo->SetHealthPaused((bool)healthPaused); + nzbInfo->SetAddUrlPaused((bool)addUrlPaused); } - else if (iFormatVersion >= 28) + else if (formatVersion >= 28) { - int iDeleted, iUnpackCleanedUpDisk, iHealthPaused, iHealthDeleted; - if (fscanf(infile, "%i,%i,%i,%i\n", &iDeleted, &iUnpackCleanedUpDisk, &iHealthPaused, &iHealthDeleted) != 4) goto error; - pNZBInfo->SetUnpackCleanedUpDisk((bool)iUnpackCleanedUpDisk); - pNZBInfo->SetHealthPaused((bool)iHealthPaused); - pNZBInfo->SetDeleteStatus(iHealthDeleted ? NZBInfo::dsHealth : iDeleted ? NZBInfo::dsManual : NZBInfo::dsNone); + int deleted, unpackCleanedUpDisk, healthPaused, healthDeleted; + if (fscanf(infile, "%i,%i,%i,%i\n", &deleted, &unpackCleanedUpDisk, &healthPaused, &healthDeleted) != 4) goto error; + nzbInfo->SetUnpackCleanedUpDisk((bool)unpackCleanedUpDisk); + nzbInfo->SetHealthPaused((bool)healthPaused); + nzbInfo->SetDeleteStatus(healthDeleted ? NZBInfo::dsHealth : deleted ? NZBInfo::dsManual : NZBInfo::dsNone); } - if (iFormatVersion >= 28) + if (formatVersion >= 28) { - int iFileCount, iParkedFileCount, iMessageCount = 0; - if (iFormatVersion >= 52) + int fileCount, parkedFileCount, messageCount = 0; + if (formatVersion >= 52) { - if (fscanf(infile, "%i,%i,%i\n", &iFileCount, &iParkedFileCount, &iMessageCount) != 3) goto error; + if (fscanf(infile, "%i,%i,%i\n", &fileCount, &parkedFileCount, &messageCount) != 3) goto error; } else { - if (fscanf(infile, "%i,%i\n", &iFileCount, &iParkedFileCount) != 2) goto error; + if (fscanf(infile, "%i,%i\n", &fileCount, &parkedFileCount) != 2) goto error; } - pNZBInfo->SetFileCount(iFileCount); - pNZBInfo->SetParkedFileCount(iParkedFileCount); - pNZBInfo->SetMessageCount(iMessageCount); + nzbInfo->SetFileCount(fileCount); + nzbInfo->SetParkedFileCount(parkedFileCount); + nzbInfo->SetMessageCount(messageCount); } else { - if (iFormatVersion >= 19) + if (formatVersion >= 19) { - int iUnpackCleanedUpDisk; - if (fscanf(infile, "%i\n", &iUnpackCleanedUpDisk) != 1) goto error; - pNZBInfo->SetUnpackCleanedUpDisk((bool)iUnpackCleanedUpDisk); + int unpackCleanedUpDisk; + if (fscanf(infile, "%i\n", &unpackCleanedUpDisk) != 1) goto error; + nzbInfo->SetUnpackCleanedUpDisk((bool)unpackCleanedUpDisk); } - int iFileCount; - if (fscanf(infile, "%i\n", &iFileCount) != 1) goto error; - pNZBInfo->SetFileCount(iFileCount); + int fileCount; + if (fscanf(infile, "%i\n", &fileCount) != 1) goto error; + nzbInfo->SetFileCount(fileCount); - if (iFormatVersion >= 10) + if (formatVersion >= 10) { - if (fscanf(infile, "%i\n", &iFileCount) != 1) goto error; - pNZBInfo->SetParkedFileCount(iFileCount); + if (fscanf(infile, "%i\n", &fileCount) != 1) goto error; + nzbInfo->SetParkedFileCount(fileCount); } } - if (iFormatVersion >= 44) + if (formatVersion >= 44) { - int iMinTime, iMaxTime; - if (fscanf(infile, "%i,%i\n", &iMinTime, &iMaxTime) != 2) goto error; - pNZBInfo->SetMinTime((time_t)iMinTime); - pNZBInfo->SetMaxTime((time_t)iMaxTime); + int minTime, maxTime; + if (fscanf(infile, "%i,%i\n", &minTime, &maxTime) != 2) goto error; + nzbInfo->SetMinTime((time_t)minTime); + nzbInfo->SetMaxTime((time_t)maxTime); } - if (iFormatVersion >= 51) + if (formatVersion >= 51) { - int iParFull, iForceParFull, iForceRepair, iExtraParBlocks = 0; - if (iFormatVersion >= 55) + int parFull, forceParFull, forceRepair, extraParBlocks = 0; + if (formatVersion >= 55) { - if (fscanf(infile, "%i,%i,%i,%i\n", &iParFull, &iForceParFull, &iForceRepair, &iExtraParBlocks) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &parFull, &forceParFull, &forceRepair, &extraParBlocks) != 4) goto error; } else { - if (fscanf(infile, "%i,%i,%i\n", &iParFull, &iForceParFull, &iForceRepair) != 3) goto error; + if (fscanf(infile, "%i,%i,%i\n", &parFull, &forceParFull, &forceRepair) != 3) goto error; } - pNZBInfo->SetParFull((bool)iParFull); - pNZBInfo->SetExtraParBlocks(iExtraParBlocks); - if (pNZBInfo->GetPostInfo()) + nzbInfo->SetParFull((bool)parFull); + nzbInfo->SetExtraParBlocks(extraParBlocks); + if (nzbInfo->GetPostInfo()) { - pNZBInfo->GetPostInfo()->SetForceParFull((bool)iForceParFull); - pNZBInfo->GetPostInfo()->SetForceRepair((bool)iForceRepair); + nzbInfo->GetPostInfo()->SetForceParFull((bool)forceParFull); + nzbInfo->GetPostInfo()->SetForceRepair((bool)forceRepair); } } if (true) // clang requires a block for goto to work { - unsigned int iFullContentHash = 0, iFilteredContentHash = 0; - if (iFormatVersion >= 34) + unsigned int fullContentHash = 0, filteredContentHash = 0; + if (formatVersion >= 34) { - if (fscanf(infile, "%u,%u\n", &iFullContentHash, &iFilteredContentHash) != 2) goto error; + if (fscanf(infile, "%u,%u\n", &fullContentHash, &filteredContentHash) != 2) goto error; } - else if (iFormatVersion >= 32) + else if (formatVersion >= 32) { - if (fscanf(infile, "%u\n", &iFullContentHash) != 1) goto error; + if (fscanf(infile, "%u\n", &fullContentHash) != 1) goto error; } - pNZBInfo->SetFullContentHash(iFullContentHash); - pNZBInfo->SetFilteredContentHash(iFilteredContentHash); + nzbInfo->SetFullContentHash(fullContentHash); + nzbInfo->SetFilteredContentHash(filteredContentHash); } - if (iFormatVersion >= 28) + if (formatVersion >= 28) { unsigned long High1, Low1, High2, Low2, High3, Low3; if (fscanf(infile, "%lu,%lu,%lu,%lu,%lu,%lu\n", &High1, &Low1, &High2, &Low2, &High3, &Low3) != 6) goto error; - pNZBInfo->SetSize(Util::JoinInt64(High1, Low1)); - pNZBInfo->SetSuccessSize(Util::JoinInt64(High2, Low2)); - pNZBInfo->SetFailedSize(Util::JoinInt64(High3, Low3)); - pNZBInfo->SetCurrentSuccessSize(pNZBInfo->GetSuccessSize()); - pNZBInfo->SetCurrentFailedSize(pNZBInfo->GetFailedSize()); + nzbInfo->SetSize(Util::JoinInt64(High1, Low1)); + nzbInfo->SetSuccessSize(Util::JoinInt64(High2, Low2)); + nzbInfo->SetFailedSize(Util::JoinInt64(High3, Low3)); + nzbInfo->SetCurrentSuccessSize(nzbInfo->GetSuccessSize()); + nzbInfo->SetCurrentFailedSize(nzbInfo->GetFailedSize()); if (fscanf(infile, "%lu,%lu,%lu,%lu,%lu,%lu\n", &High1, &Low1, &High2, &Low2, &High3, &Low3) != 6) goto error; - pNZBInfo->SetParSize(Util::JoinInt64(High1, Low1)); - pNZBInfo->SetParSuccessSize(Util::JoinInt64(High2, Low2)); - pNZBInfo->SetParFailedSize(Util::JoinInt64(High3, Low3)); - pNZBInfo->SetParCurrentSuccessSize(pNZBInfo->GetParSuccessSize()); - pNZBInfo->SetParCurrentFailedSize(pNZBInfo->GetParFailedSize()); + nzbInfo->SetParSize(Util::JoinInt64(High1, Low1)); + nzbInfo->SetParSuccessSize(Util::JoinInt64(High2, Low2)); + nzbInfo->SetParFailedSize(Util::JoinInt64(High3, Low3)); + nzbInfo->SetParCurrentSuccessSize(nzbInfo->GetParSuccessSize()); + nzbInfo->SetParCurrentFailedSize(nzbInfo->GetParFailedSize()); } else { unsigned long High, Low; if (fscanf(infile, "%lu,%lu\n", &High, &Low) != 2) goto error; - pNZBInfo->SetSize(Util::JoinInt64(High, Low)); + nzbInfo->SetSize(Util::JoinInt64(High, Low)); } - if (iFormatVersion >= 30) + if (formatVersion >= 30) { - int iTotalArticles, iSuccessArticles, iFailedArticles; - if (fscanf(infile, "%i,%i,%i\n", &iTotalArticles, &iSuccessArticles, &iFailedArticles) != 3) goto error; - pNZBInfo->SetTotalArticles(iTotalArticles); - pNZBInfo->SetSuccessArticles(iSuccessArticles); - pNZBInfo->SetFailedArticles(iFailedArticles); - pNZBInfo->SetCurrentSuccessArticles(iSuccessArticles); - pNZBInfo->SetCurrentFailedArticles(iFailedArticles); + int totalArticles, successArticles, failedArticles; + if (fscanf(infile, "%i,%i,%i\n", &totalArticles, &successArticles, &failedArticles) != 3) goto error; + nzbInfo->SetTotalArticles(totalArticles); + nzbInfo->SetSuccessArticles(successArticles); + nzbInfo->SetFailedArticles(failedArticles); + nzbInfo->SetCurrentSuccessArticles(successArticles); + nzbInfo->SetCurrentFailedArticles(failedArticles); } - if (iFormatVersion >= 31) + if (formatVersion >= 31) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (iFormatVersion < 36) ConvertDupeKey(buf, sizeof(buf)); - pNZBInfo->SetDupeKey(buf); + if (formatVersion < 36) ConvertDupeKey(buf, sizeof(buf)); + nzbInfo->SetDupeKey(buf); } if (true) // clang requires a block for goto to work { - int iDupeMode = 0, iDupeScore = 0; - if (iFormatVersion >= 39) + int dupeMode = 0, dupeScore = 0; + if (formatVersion >= 39) { - if (fscanf(infile, "%i,%i\n", &iDupeMode, &iDupeScore) != 2) goto error; + if (fscanf(infile, "%i,%i\n", &dupeMode, &dupeScore) != 2) goto error; } - else if (iFormatVersion >= 31) + else if (formatVersion >= 31) { - int iDupe; - if (fscanf(infile, "%i,%i,%i\n", &iDupe, &iDupeMode, &iDupeScore) != 3) goto error; + int dupe; + if (fscanf(infile, "%i,%i,%i\n", &dupe, &dupeMode, &dupeScore) != 3) goto error; } - pNZBInfo->SetDupeMode((EDupeMode)iDupeMode); - pNZBInfo->SetDupeScore(iDupeScore); + nzbInfo->SetDupeMode((EDupeMode)dupeMode); + nzbInfo->SetDupeScore(dupeScore); } - if (iFormatVersion >= 48) + if (formatVersion >= 48) { - unsigned long High1, Low1, iDownloadSec, iPostTotalSec, iParSec, iRepairSec, iUnpackSec; - if (fscanf(infile, "%lu,%lu,%i,%i,%i,%i,%i\n", &High1, &Low1, &iDownloadSec, &iPostTotalSec, &iParSec, &iRepairSec, &iUnpackSec) != 7) goto error; - pNZBInfo->SetDownloadedSize(Util::JoinInt64(High1, Low1)); - pNZBInfo->SetDownloadSec(iDownloadSec); - pNZBInfo->SetPostTotalSec(iPostTotalSec); - pNZBInfo->SetParSec(iParSec); - pNZBInfo->SetRepairSec(iRepairSec); - pNZBInfo->SetUnpackSec(iUnpackSec); + unsigned long High1, Low1, downloadSec, postTotalSec, parSec, repairSec, unpackSec; + if (fscanf(infile, "%lu,%lu,%i,%i,%i,%i,%i\n", &High1, &Low1, &downloadSec, &postTotalSec, &parSec, &repairSec, &unpackSec) != 7) goto error; + nzbInfo->SetDownloadedSize(Util::JoinInt64(High1, Low1)); + nzbInfo->SetDownloadSec(downloadSec); + nzbInfo->SetPostTotalSec(postTotalSec); + nzbInfo->SetParSec(parSec); + nzbInfo->SetRepairSec(repairSec); + nzbInfo->SetUnpackSec(unpackSec); } - if (iFormatVersion >= 4) + if (formatVersion >= 4) { - int iFileCount; - if (fscanf(infile, "%i\n", &iFileCount) != 1) goto error; - for (int i = 0; i < iFileCount; i++) + int fileCount; + if (fscanf(infile, "%i\n", &fileCount) != 1) goto error; + for (int i = 0; i < fileCount; i++) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - int iID = 0; - char* szFileName = buf; - int iStatus = 0; - unsigned long lCrc = 0; + int id = 0; + char* fileName = buf; + int status = 0; + unsigned long crc = 0; - if (iFormatVersion >= 49) + if (formatVersion >= 49) { - if (iFormatVersion >= 50) + if (formatVersion >= 50) { - if (sscanf(buf, "%i,%i,%lu", &iID, &iStatus, &lCrc) != 3) goto error; - szFileName = strchr(buf, ','); - if (szFileName) szFileName = strchr(szFileName+1, ','); - if (szFileName) szFileName = strchr(szFileName+1, ','); + if (sscanf(buf, "%i,%i,%lu", &id, &status, &crc) != 3) goto error; + fileName = strchr(buf, ','); + if (fileName) fileName = strchr(fileName+1, ','); + if (fileName) fileName = strchr(fileName+1, ','); } else { - if (sscanf(buf, "%i,%lu", &iStatus, &lCrc) != 2) goto error; - szFileName = strchr(buf + 2, ','); + if (sscanf(buf, "%i,%lu", &status, &crc) != 2) goto error; + fileName = strchr(buf + 2, ','); } - if (szFileName) + if (fileName) { - szFileName++; + fileName++; } } - pNZBInfo->GetCompletedFiles()->push_back(new CompletedFile(iID, szFileName, (CompletedFile::EStatus)iStatus, lCrc)); + nzbInfo->GetCompletedFiles()->push_back(new CompletedFile(id, fileName, (CompletedFile::EStatus)status, crc)); } } - if (iFormatVersion >= 6) + if (formatVersion >= 6) { - int iParameterCount; - if (fscanf(infile, "%i\n", &iParameterCount) != 1) goto error; - for (int i = 0; i < iParameterCount; i++) + int parameterCount; + if (fscanf(infile, "%i\n", ¶meterCount) != 1) goto error; + for (int i = 0; i < parameterCount; i++) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - char* szValue = strchr(buf, '='); - if (szValue) + char* value = strchr(buf, '='); + if (value) { - *szValue = '\0'; - szValue++; - pNZBInfo->GetParameters()->SetParameter(buf, szValue); + *value = '\0'; + value++; + nzbInfo->GetParameters()->SetParameter(buf, value); } } } - if (iFormatVersion >= 23) + if (formatVersion >= 23) { - int iScriptCount; - if (fscanf(infile, "%i\n", &iScriptCount) != 1) goto error; - for (int i = 0; i < iScriptCount; i++) + int scriptCount; + if (fscanf(infile, "%i\n", &scriptCount) != 1) goto error; + for (int i = 0; i < scriptCount; i++) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - char* szScriptName = strchr(buf, ','); - if (szScriptName) + char* scriptName = strchr(buf, ','); + if (scriptName) { - szScriptName++; - int iStatus = atoi(buf); - if (iStatus > 1 && iFormatVersion < 25) iStatus--; - pNZBInfo->GetScriptStatuses()->Add(szScriptName, (ScriptStatus::EStatus)iStatus); + scriptName++; + int status = atoi(buf); + if (status > 1 && formatVersion < 25) status--; + nzbInfo->GetScriptStatuses()->Add(scriptName, (ScriptStatus::EStatus)status); } } } - if (iFormatVersion >= 30) + if (formatVersion >= 30) { - if (!LoadServerStats(pNZBInfo->GetServerStats(), pServers, infile)) goto error; - pNZBInfo->GetCurrentServerStats()->ListOp(pNZBInfo->GetServerStats(), ServerStatList::soSet); + if (!LoadServerStats(nzbInfo->GetServerStats(), servers, infile)) goto error; + nzbInfo->GetCurrentServerStats()->ListOp(nzbInfo->GetServerStats(), ServerStatList::soSet); } - if (iFormatVersion >= 11 && iFormatVersion < 52) + if (formatVersion >= 11 && formatVersion < 52) { - int iLogCount; - if (fscanf(infile, "%i\n", &iLogCount) != 1) goto error; - for (int i = 0; i < iLogCount; i++) + int logCount; + if (fscanf(infile, "%i\n", &logCount) != 1) goto error; + for (int i = 0; i < logCount; i++) { if (!fgets(buf, sizeof(buf), infile)) goto error; } } - if (iFormatVersion < 26) + if (formatVersion < 26) { - NZBParameter* pUnpackParameter = pNZBInfo->GetParameters()->Find("*Unpack:", false); - if (!pUnpackParameter) + NZBParameter* unpackParameter = nzbInfo->GetParameters()->Find("*Unpack:", false); + if (!unpackParameter) { - pNZBInfo->GetParameters()->SetParameter("*Unpack:", g_pOptions->GetUnpack() ? "yes" : "no"); + nzbInfo->GetParameters()->SetParameter("*Unpack:", g_pOptions->GetUnpack() ? "yes" : "no"); } } - if (iFormatVersion >= 43) + if (formatVersion >= 43) { - int iFileCount; - if (fscanf(infile, "%i\n", &iFileCount) != 1) goto error; - for (int i = 0; i < iFileCount; i++) + int fileCount; + if (fscanf(infile, "%i\n", &fileCount) != 1) goto error; + for (int i = 0; i < fileCount; i++) { - unsigned int id, paused, iTime = 0; - int iPriority = 0, iExtraPriority = 0; + unsigned int id, paused, time = 0; + int priority = 0, extraPriority = 0; - if (iFormatVersion >= 44) + if (formatVersion >= 44) { - if (fscanf(infile, "%i,%i,%i,%i\n", &id, &paused, &iTime, &iExtraPriority) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &id, &paused, &time, &extraPriority) != 4) goto error; } else { - if (fscanf(infile, "%i,%i,%i,%i,%i\n", &id, &paused, &iTime, &iPriority, &iExtraPriority) != 5) goto error; - pNZBInfo->SetPriority(iPriority); + if (fscanf(infile, "%i,%i,%i,%i,%i\n", &id, &paused, &time, &priority, &extraPriority) != 5) goto error; + nzbInfo->SetPriority(priority); } char fileName[1024]; snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), id); fileName[1024-1] = '\0'; - FileInfo* pFileInfo = new FileInfo(); - bool res = LoadFileInfo(pFileInfo, fileName, true, false); + FileInfo* fileInfo = new FileInfo(); + bool res = LoadFileInfo(fileInfo, fileName, true, false); if (res) { - pFileInfo->SetID(id); - pFileInfo->SetPaused(paused); - pFileInfo->SetTime(iTime); - pFileInfo->SetExtraPriority(iExtraPriority != 0); - pFileInfo->SetNZBInfo(pNZBInfo); - if (iFormatVersion < 30) + fileInfo->SetID(id); + fileInfo->SetPaused(paused); + fileInfo->SetTime(time); + fileInfo->SetExtraPriority(extraPriority != 0); + fileInfo->SetNZBInfo(nzbInfo); + if (formatVersion < 30) { - pNZBInfo->SetTotalArticles(pNZBInfo->GetTotalArticles() + pFileInfo->GetTotalArticles()); + nzbInfo->SetTotalArticles(nzbInfo->GetTotalArticles() + fileInfo->GetTotalArticles()); } - pNZBInfo->GetFileList()->push_back(pFileInfo); + nzbInfo->GetFileList()->push_back(fileInfo); } else { - delete pFileInfo; + delete fileInfo; } } } @@ -1054,7 +1054,7 @@ error: return false; } -bool DiskState::LoadFileQueue12(NZBList* pNZBList, NZBList* pSortList, FILE* infile, int iFormatVersion) +bool DiskState::LoadFileQueue12(NZBList* nzbList, NZBList* sortList, FILE* infile, int formatVersion) { debug("Loading file queue from disk"); @@ -1062,55 +1062,55 @@ bool DiskState::LoadFileQueue12(NZBList* pNZBList, NZBList* pSortList, FILE* inf if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - unsigned int id, iNZBIndex, paused; - unsigned int iTime = 0; - int iPriority = 0, iExtraPriority = 0; - if (iFormatVersion >= 17) + unsigned int id, nzbIndex, paused; + unsigned int time = 0; + int priority = 0, extraPriority = 0; + if (formatVersion >= 17) { - if (fscanf(infile, "%i,%i,%i,%i,%i,%i\n", &id, &iNZBIndex, &paused, &iTime, &iPriority, &iExtraPriority) != 6) goto error; + if (fscanf(infile, "%i,%i,%i,%i,%i,%i\n", &id, &nzbIndex, &paused, &time, &priority, &extraPriority) != 6) goto error; } - else if (iFormatVersion >= 14) + else if (formatVersion >= 14) { - if (fscanf(infile, "%i,%i,%i,%i,%i\n", &id, &iNZBIndex, &paused, &iTime, &iPriority) != 5) goto error; + if (fscanf(infile, "%i,%i,%i,%i,%i\n", &id, &nzbIndex, &paused, &time, &priority) != 5) goto error; } - else if (iFormatVersion >= 12) + else if (formatVersion >= 12) { - if (fscanf(infile, "%i,%i,%i,%i\n", &id, &iNZBIndex, &paused, &iTime) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &id, &nzbIndex, &paused, &time) != 4) goto error; } else { - if (fscanf(infile, "%i,%i,%i\n", &id, &iNZBIndex, &paused) != 3) goto error; + if (fscanf(infile, "%i,%i,%i\n", &id, &nzbIndex, &paused) != 3) goto error; } - if (iNZBIndex > pNZBList->size()) goto error; + if (nzbIndex > nzbList->size()) goto error; char fileName[1024]; snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), id); fileName[1024-1] = '\0'; - FileInfo* pFileInfo = new FileInfo(); - bool res = LoadFileInfo(pFileInfo, fileName, true, false); + FileInfo* fileInfo = new FileInfo(); + bool res = LoadFileInfo(fileInfo, fileName, true, false); if (res) { - NZBInfo* pNZBInfo = pNZBList->at(iNZBIndex - 1); - pNZBInfo->SetPriority(iPriority); - pFileInfo->SetID(id); - pFileInfo->SetPaused(paused); - pFileInfo->SetTime(iTime); - pFileInfo->SetExtraPriority(iExtraPriority != 0); - pFileInfo->SetNZBInfo(pNZBInfo); - if (iFormatVersion < 30) + NZBInfo* nzbInfo = nzbList->at(nzbIndex - 1); + nzbInfo->SetPriority(priority); + fileInfo->SetID(id); + fileInfo->SetPaused(paused); + fileInfo->SetTime(time); + fileInfo->SetExtraPriority(extraPriority != 0); + fileInfo->SetNZBInfo(nzbInfo); + if (formatVersion < 30) { - pNZBInfo->SetTotalArticles(pNZBInfo->GetTotalArticles() + pFileInfo->GetTotalArticles()); + nzbInfo->SetTotalArticles(nzbInfo->GetTotalArticles() + fileInfo->GetTotalArticles()); } - pNZBInfo->GetFileList()->push_back(pFileInfo); + nzbInfo->GetFileList()->push_back(fileInfo); - if (pSortList && std::find(pSortList->begin(), pSortList->end(), pNZBInfo) == pSortList->end()) + if (sortList && std::find(sortList->begin(), sortList->end(), nzbInfo) == sortList->end()) { - pSortList->push_back(pNZBInfo); + sortList->push_back(nzbInfo); } } else { - delete pFileInfo; + delete fileInfo; } } @@ -1121,34 +1121,34 @@ error: return false; } -void DiskState::SaveServerStats(ServerStatList* pServerStatList, FILE* outfile) +void DiskState::SaveServerStats(ServerStatList* serverStatList, FILE* outfile) { - fprintf(outfile, "%i\n", (int)pServerStatList->size()); - for (ServerStatList::iterator it = pServerStatList->begin(); it != pServerStatList->end(); it++) + fprintf(outfile, "%i\n", (int)serverStatList->size()); + for (ServerStatList::iterator it = serverStatList->begin(); it != serverStatList->end(); it++) { - ServerStat* pServerStat = *it; - fprintf(outfile, "%i,%i,%i\n", pServerStat->GetServerID(), pServerStat->GetSuccessArticles(), pServerStat->GetFailedArticles()); + ServerStat* serverStat = *it; + fprintf(outfile, "%i,%i,%i\n", serverStat->GetServerID(), serverStat->GetSuccessArticles(), serverStat->GetFailedArticles()); } } -bool DiskState::LoadServerStats(ServerStatList* pServerStatList, Servers* pServers, FILE* infile) +bool DiskState::LoadServerStats(ServerStatList* serverStatList, Servers* servers, FILE* infile) { - int iStatCount; - if (fscanf(infile, "%i\n", &iStatCount) != 1) goto error; - for (int i = 0; i < iStatCount; i++) + int statCount; + if (fscanf(infile, "%i\n", &statCount) != 1) goto error; + for (int i = 0; i < statCount; i++) { - int iServerID, iSuccessArticles, iFailedArticles; - if (fscanf(infile, "%i,%i,%i\n", &iServerID, &iSuccessArticles, &iFailedArticles) != 3) goto error; + int serverId, successArticles, failedArticles; + if (fscanf(infile, "%i,%i,%i\n", &serverId, &successArticles, &failedArticles) != 3) goto error; - if (pServers) + if (servers) { // find server (id could change if config file was edited) - for (Servers::iterator it = pServers->begin(); it != pServers->end(); it++) + for (Servers::iterator it = servers->begin(); it != servers->end(); it++) { - NewsServer* pNewsServer = *it; - if (pNewsServer->GetStateID() == iServerID) + NewsServer* newsServer = *it; + if (newsServer->GetStateID() == serverId) { - pServerStatList->StatOp(pNewsServer->GetID(), iSuccessArticles, iFailedArticles, ServerStatList::soSet); + serverStatList->StatOp(newsServer->GetID(), successArticles, failedArticles, ServerStatList::soSet); } } } @@ -1161,87 +1161,87 @@ error: return false; } -bool DiskState::SaveFile(FileInfo* pFileInfo) +bool DiskState::SaveFile(FileInfo* fileInfo) { char fileName[1024]; - snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), pFileInfo->GetID()); + snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), fileInfo->GetID()); fileName[1024-1] = '\0'; - return SaveFileInfo(pFileInfo, fileName); + return SaveFileInfo(fileInfo, fileName); } -bool DiskState::SaveFileInfo(FileInfo* pFileInfo, const char* szFilename) +bool DiskState::SaveFileInfo(FileInfo* fileInfo, const char* filename) { debug("Saving FileInfo to disk"); - FILE* outfile = fopen(szFilename, FOPEN_WB); + FILE* outfile = fopen(filename, FOPEN_WB); if (!outfile) { - error("Error saving diskstate: could not create file %s", szFilename); + error("Error saving diskstate: could not create file %s", filename); return false; } fprintf(outfile, "%s%i\n", FORMATVERSION_SIGNATURE, 3); - fprintf(outfile, "%s\n", pFileInfo->GetSubject()); - fprintf(outfile, "%s\n", pFileInfo->GetFilename()); + fprintf(outfile, "%s\n", fileInfo->GetSubject()); + fprintf(outfile, "%s\n", fileInfo->GetFilename()); unsigned long High, Low; - Util::SplitInt64(pFileInfo->GetSize(), &High, &Low); + Util::SplitInt64(fileInfo->GetSize(), &High, &Low); fprintf(outfile, "%lu,%lu\n", High, Low); - Util::SplitInt64(pFileInfo->GetMissedSize(), &High, &Low); + Util::SplitInt64(fileInfo->GetMissedSize(), &High, &Low); fprintf(outfile, "%lu,%lu\n", High, Low); - fprintf(outfile, "%i\n", (int)pFileInfo->GetParFile()); - fprintf(outfile, "%i,%i\n", pFileInfo->GetTotalArticles(), pFileInfo->GetMissedArticles()); + fprintf(outfile, "%i\n", (int)fileInfo->GetParFile()); + fprintf(outfile, "%i,%i\n", fileInfo->GetTotalArticles(), fileInfo->GetMissedArticles()); - fprintf(outfile, "%i\n", (int)pFileInfo->GetGroups()->size()); - for (FileInfo::Groups::iterator it = pFileInfo->GetGroups()->begin(); it != pFileInfo->GetGroups()->end(); it++) + fprintf(outfile, "%i\n", (int)fileInfo->GetGroups()->size()); + for (FileInfo::Groups::iterator it = fileInfo->GetGroups()->begin(); it != fileInfo->GetGroups()->end(); it++) { fprintf(outfile, "%s\n", *it); } - fprintf(outfile, "%i\n", (int)pFileInfo->GetArticles()->size()); - for (FileInfo::Articles::iterator it = pFileInfo->GetArticles()->begin(); it != pFileInfo->GetArticles()->end(); it++) + fprintf(outfile, "%i\n", (int)fileInfo->GetArticles()->size()); + for (FileInfo::Articles::iterator it = fileInfo->GetArticles()->begin(); it != fileInfo->GetArticles()->end(); it++) { - ArticleInfo* pArticleInfo = *it; - fprintf(outfile, "%i,%i\n", pArticleInfo->GetPartNumber(), pArticleInfo->GetSize()); - fprintf(outfile, "%s\n", pArticleInfo->GetMessageID()); + ArticleInfo* articleInfo = *it; + fprintf(outfile, "%i,%i\n", articleInfo->GetPartNumber(), articleInfo->GetSize()); + fprintf(outfile, "%s\n", articleInfo->GetMessageID()); } fclose(outfile); return true; } -bool DiskState::LoadArticles(FileInfo* pFileInfo) +bool DiskState::LoadArticles(FileInfo* fileInfo) { char fileName[1024]; - snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), pFileInfo->GetID()); + snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), fileInfo->GetID()); fileName[1024-1] = '\0'; - return LoadFileInfo(pFileInfo, fileName, false, true); + return LoadFileInfo(fileInfo, fileName, false, true); } -bool DiskState::LoadFileInfo(FileInfo* pFileInfo, const char * szFilename, bool bFileSummary, bool bArticles) +bool DiskState::LoadFileInfo(FileInfo* fileInfo, const char * filename, bool fileSummary, bool articles) { debug("Loading FileInfo from disk"); - FILE* infile = fopen(szFilename, FOPEN_RB); + FILE* infile = fopen(filename, FOPEN_RB); if (!infile) { - error("Error reading diskstate: could not open file %s", szFilename); + error("Error reading diskstate: could not open file %s", filename); return false; } char buf[1024]; - int iFormatVersion = 0; + int formatVersion = 0; if (fgets(buf, sizeof(buf), infile)) { if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - iFormatVersion = ParseFormatVersion(buf); - if (iFormatVersion > 3) + formatVersion = ParseFormatVersion(buf); + if (formatVersion > 3) { error("Could not load diskstate due to file version mismatch"); goto error; @@ -1252,47 +1252,47 @@ bool DiskState::LoadFileInfo(FileInfo* pFileInfo, const char * szFilename, bool goto error; } - if (iFormatVersion >= 2) + if (formatVersion >= 2) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' } - if (bFileSummary) pFileInfo->SetSubject(buf); + if (fileSummary) fileInfo->SetSubject(buf); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (bFileSummary) pFileInfo->SetFilename(buf); + if (fileSummary) fileInfo->SetFilename(buf); - if (iFormatVersion < 2) + if (formatVersion < 2) { - int iFilenameConfirmed; - if (fscanf(infile, "%i\n", &iFilenameConfirmed) != 1) goto error; - if (bFileSummary) pFileInfo->SetFilenameConfirmed(iFilenameConfirmed); + int filenameConfirmed; + if (fscanf(infile, "%i\n", &filenameConfirmed) != 1) goto error; + if (fileSummary) fileInfo->SetFilenameConfirmed(filenameConfirmed); } unsigned long High, Low; if (fscanf(infile, "%lu,%lu\n", &High, &Low) != 2) goto error; - if (bFileSummary) pFileInfo->SetSize(Util::JoinInt64(High, Low)); - if (bFileSummary) pFileInfo->SetRemainingSize(pFileInfo->GetSize()); + if (fileSummary) fileInfo->SetSize(Util::JoinInt64(High, Low)); + if (fileSummary) fileInfo->SetRemainingSize(fileInfo->GetSize()); - if (iFormatVersion >= 2) + if (formatVersion >= 2) { if (fscanf(infile, "%lu,%lu\n", &High, &Low) != 2) goto error; - if (bFileSummary) pFileInfo->SetMissedSize(Util::JoinInt64(High, Low)); - if (bFileSummary) pFileInfo->SetRemainingSize(pFileInfo->GetSize() - pFileInfo->GetMissedSize()); + if (fileSummary) fileInfo->SetMissedSize(Util::JoinInt64(High, Low)); + if (fileSummary) fileInfo->SetRemainingSize(fileInfo->GetSize() - fileInfo->GetMissedSize()); - int iParFile; - if (fscanf(infile, "%i\n", &iParFile) != 1) goto error; - if (bFileSummary) pFileInfo->SetParFile((bool)iParFile); + int parFile; + if (fscanf(infile, "%i\n", &parFile) != 1) goto error; + if (fileSummary) fileInfo->SetParFile((bool)parFile); } - if (iFormatVersion >= 3) + if (formatVersion >= 3) { - int iTotalArticles, iMissedArticles; - if (fscanf(infile, "%i,%i\n", &iTotalArticles, &iMissedArticles) != 2) goto error; - if (bFileSummary) pFileInfo->SetTotalArticles(iTotalArticles); - if (bFileSummary) pFileInfo->SetMissedArticles(iMissedArticles); + int totalArticles, missedArticles; + if (fscanf(infile, "%i,%i\n", &totalArticles, &missedArticles) != 2) goto error; + if (fileSummary) fileInfo->SetTotalArticles(totalArticles); + if (fileSummary) fileInfo->SetMissedArticles(missedArticles); } int size; @@ -1301,17 +1301,17 @@ bool DiskState::LoadFileInfo(FileInfo* pFileInfo, const char * szFilename, bool { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (bFileSummary) pFileInfo->GetGroups()->push_back(strdup(buf)); + if (fileSummary) fileInfo->GetGroups()->push_back(strdup(buf)); } if (fscanf(infile, "%i\n", &size) != 1) goto error; - if (iFormatVersion < 3 && bFileSummary) + if (formatVersion < 3 && fileSummary) { - pFileInfo->SetTotalArticles(size); + fileInfo->SetTotalArticles(size); } - if (bArticles) + if (articles) { for (int i = 0; i < size; i++) { @@ -1321,11 +1321,11 @@ bool DiskState::LoadFileInfo(FileInfo* pFileInfo, const char * szFilename, bool if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - ArticleInfo* pArticleInfo = new ArticleInfo(); - pArticleInfo->SetPartNumber(PartNumber); - pArticleInfo->SetSize(PartSize); - pArticleInfo->SetMessageID(buf); - pFileInfo->GetArticles()->push_back(pArticleInfo); + ArticleInfo* articleInfo = new ArticleInfo(); + articleInfo->SetPartNumber(PartNumber); + articleInfo->SetSize(PartSize); + articleInfo->SetMessageID(buf); + fileInfo->GetArticles()->push_back(articleInfo); } } @@ -1334,74 +1334,74 @@ bool DiskState::LoadFileInfo(FileInfo* pFileInfo, const char * szFilename, bool error: fclose(infile); - error("Error reading diskstate for file %s", szFilename); + error("Error reading diskstate for file %s", filename); return false; } -bool DiskState::SaveFileState(FileInfo* pFileInfo, bool bCompleted) +bool DiskState::SaveFileState(FileInfo* fileInfo, bool completed) { debug("Saving FileState to disk"); - char szFilename[1024]; - snprintf(szFilename, 1024, "%s%i%s", g_pOptions->GetQueueDir(), pFileInfo->GetID(), bCompleted ? "c" : "s"); - szFilename[1024-1] = '\0'; + char filename[1024]; + snprintf(filename, 1024, "%s%i%s", g_pOptions->GetQueueDir(), fileInfo->GetID(), completed ? "c" : "s"); + filename[1024-1] = '\0'; - FILE* outfile = fopen(szFilename, FOPEN_WB); + FILE* outfile = fopen(filename, FOPEN_WB); if (!outfile) { - error("Error saving diskstate: could not create file %s", szFilename); + error("Error saving diskstate: could not create file %s", filename); return false; } fprintf(outfile, "%s%i\n", FORMATVERSION_SIGNATURE, 2); - fprintf(outfile, "%i,%i\n", pFileInfo->GetSuccessArticles(), pFileInfo->GetFailedArticles()); + fprintf(outfile, "%i,%i\n", fileInfo->GetSuccessArticles(), fileInfo->GetFailedArticles()); unsigned long High1, Low1, High2, Low2, High3, Low3; - Util::SplitInt64(pFileInfo->GetRemainingSize(), &High1, &Low1); - Util::SplitInt64(pFileInfo->GetSuccessSize(), &High2, &Low2); - Util::SplitInt64(pFileInfo->GetFailedSize(), &High3, &Low3); + Util::SplitInt64(fileInfo->GetRemainingSize(), &High1, &Low1); + Util::SplitInt64(fileInfo->GetSuccessSize(), &High2, &Low2); + Util::SplitInt64(fileInfo->GetFailedSize(), &High3, &Low3); fprintf(outfile, "%lu,%lu,%lu,%lu,%lu,%lu\n", High1, Low1, High2, Low2, High3, Low3); - SaveServerStats(pFileInfo->GetServerStats(), outfile); + SaveServerStats(fileInfo->GetServerStats(), outfile); - fprintf(outfile, "%i\n", (int)pFileInfo->GetArticles()->size()); - for (FileInfo::Articles::iterator it = pFileInfo->GetArticles()->begin(); it != pFileInfo->GetArticles()->end(); it++) + fprintf(outfile, "%i\n", (int)fileInfo->GetArticles()->size()); + for (FileInfo::Articles::iterator it = fileInfo->GetArticles()->begin(); it != fileInfo->GetArticles()->end(); it++) { - ArticleInfo* pArticleInfo = *it; - fprintf(outfile, "%i,%lu,%i,%lu\n", (int)pArticleInfo->GetStatus(), (unsigned long)pArticleInfo->GetSegmentOffset(), - pArticleInfo->GetSegmentSize(), (unsigned long)pArticleInfo->GetCrc()); + ArticleInfo* articleInfo = *it; + fprintf(outfile, "%i,%lu,%i,%lu\n", (int)articleInfo->GetStatus(), (unsigned long)articleInfo->GetSegmentOffset(), + articleInfo->GetSegmentSize(), (unsigned long)articleInfo->GetCrc()); } fclose(outfile); return true; } -bool DiskState::LoadFileState(FileInfo* pFileInfo, Servers* pServers, bool bCompleted) +bool DiskState::LoadFileState(FileInfo* fileInfo, Servers* servers, bool completed) { - char szFilename[1024]; - snprintf(szFilename, 1024, "%s%i%s", g_pOptions->GetQueueDir(), pFileInfo->GetID(), bCompleted ? "c" : "s"); - szFilename[1024-1] = '\0'; + char filename[1024]; + snprintf(filename, 1024, "%s%i%s", g_pOptions->GetQueueDir(), fileInfo->GetID(), completed ? "c" : "s"); + filename[1024-1] = '\0'; - bool bHasArticles = !pFileInfo->GetArticles()->empty(); + bool hasArticles = !fileInfo->GetArticles()->empty(); - FILE* infile = fopen(szFilename, FOPEN_RB); + FILE* infile = fopen(filename, FOPEN_RB); if (!infile) { - error("Error reading diskstate: could not open file %s", szFilename); + error("Error reading diskstate: could not open file %s", filename); return false; } char buf[1024]; - int iFormatVersion = 0; + int formatVersion = 0; if (fgets(buf, sizeof(buf), infile)) { if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - iFormatVersion = ParseFormatVersion(buf); - if (iFormatVersion > 2) + formatVersion = ParseFormatVersion(buf); + if (formatVersion > 2) { error("Could not load diskstate due to file version mismatch"); goto error; @@ -1412,115 +1412,115 @@ bool DiskState::LoadFileState(FileInfo* pFileInfo, Servers* pServers, bool bComp goto error; } - int iSuccessArticles, iFailedArticles; - if (fscanf(infile, "%i,%i\n", &iSuccessArticles, &iFailedArticles) != 2) goto error; - pFileInfo->SetSuccessArticles(iSuccessArticles); - pFileInfo->SetFailedArticles(iFailedArticles); + int successArticles, failedArticles; + if (fscanf(infile, "%i,%i\n", &successArticles, &failedArticles) != 2) goto error; + fileInfo->SetSuccessArticles(successArticles); + fileInfo->SetFailedArticles(failedArticles); unsigned long High1, Low1, High2, Low2, High3, Low3; if (fscanf(infile, "%lu,%lu,%lu,%lu,%lu,%lu\n", &High1, &Low1, &High2, &Low2, &High3, &Low3) != 6) goto error; - pFileInfo->SetRemainingSize(Util::JoinInt64(High1, Low1)); - pFileInfo->SetSuccessSize(Util::JoinInt64(High2, Low3)); - pFileInfo->SetFailedSize(Util::JoinInt64(High3, Low3)); + fileInfo->SetRemainingSize(Util::JoinInt64(High1, Low1)); + fileInfo->SetSuccessSize(Util::JoinInt64(High2, Low3)); + fileInfo->SetFailedSize(Util::JoinInt64(High3, Low3)); - if (!LoadServerStats(pFileInfo->GetServerStats(), pServers, infile)) goto error; + if (!LoadServerStats(fileInfo->GetServerStats(), servers, infile)) goto error; - int iCompletedArticles; - iCompletedArticles = 0; //clang requires initialization in a separate line (due to goto statements) + int completedArticles; + completedArticles = 0; //clang requires initialization in a separate line (due to goto statements) int size; if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - if (!bHasArticles) + if (!hasArticles) { - pFileInfo->GetArticles()->push_back(new ArticleInfo()); + fileInfo->GetArticles()->push_back(new ArticleInfo()); } - ArticleInfo* pa = pFileInfo->GetArticles()->at(i); + ArticleInfo* pa = fileInfo->GetArticles()->at(i); - int iStatus; + int statusInt; - if (iFormatVersion >= 2) + if (formatVersion >= 2) { - unsigned long iSegmentOffset, iCrc; - int iSegmentSize; - if (fscanf(infile, "%i,%lu,%i,%lu\n", &iStatus, &iSegmentOffset, &iSegmentSize, &iCrc) != 4) goto error; - pa->SetSegmentOffset(iSegmentOffset); - pa->SetSegmentSize(iSegmentSize); - pa->SetCrc(iCrc); + unsigned long segmentOffset, crc; + int segmentSize; + if (fscanf(infile, "%i,%lu,%i,%lu\n", &statusInt, &segmentOffset, &segmentSize, &crc) != 4) goto error; + pa->SetSegmentOffset(segmentOffset); + pa->SetSegmentSize(segmentSize); + pa->SetCrc(crc); } else { - if (fscanf(infile, "%i\n", &iStatus) != 1) goto error; + if (fscanf(infile, "%i\n", &statusInt) != 1) goto error; } - ArticleInfo::EStatus eStatus = (ArticleInfo::EStatus)iStatus; + ArticleInfo::EStatus status = (ArticleInfo::EStatus)statusInt; - if (eStatus == ArticleInfo::aiRunning) + if (status == ArticleInfo::aiRunning) { - eStatus = ArticleInfo::aiUndefined; + status = ArticleInfo::aiUndefined; } // don't allow all articles be completed or the file will stuck. // such states should never be saved on disk but just in case. - if (iCompletedArticles == size - 1 && !bCompleted) + if (completedArticles == size - 1 && !completed) { - eStatus = ArticleInfo::aiUndefined; + status = ArticleInfo::aiUndefined; } - if (eStatus != ArticleInfo::aiUndefined) + if (status != ArticleInfo::aiUndefined) { - iCompletedArticles++; + completedArticles++; } - pa->SetStatus(eStatus); + pa->SetStatus(status); } - pFileInfo->SetCompletedArticles(iCompletedArticles); + fileInfo->SetCompletedArticles(completedArticles); fclose(infile); return true; error: fclose(infile); - error("Error reading diskstate for file %s", szFilename); + error("Error reading diskstate for file %s", filename); return false; } -void DiskState::DiscardFiles(NZBInfo* pNZBInfo) +void DiskState::DiscardFiles(NZBInfo* nzbInfo) { - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - DiscardFile(pFileInfo, true, true, true); + FileInfo* fileInfo = *it; + DiscardFile(fileInfo, true, true, true); } - char szFilename[1024]; + char filename[1024]; - for (CompletedFiles::iterator it = pNZBInfo->GetCompletedFiles()->begin(); it != pNZBInfo->GetCompletedFiles()->end(); it++) + for (CompletedFiles::iterator it = nzbInfo->GetCompletedFiles()->begin(); it != nzbInfo->GetCompletedFiles()->end(); it++) { - CompletedFile* pCompletedFile = *it; - if (pCompletedFile->GetStatus() != CompletedFile::cfSuccess && pCompletedFile->GetID() > 0) + CompletedFile* completedFile = *it; + if (completedFile->GetStatus() != CompletedFile::cfSuccess && completedFile->GetID() > 0) { - snprintf(szFilename, 1024, "%s%i", g_pOptions->GetQueueDir(), pCompletedFile->GetID()); - szFilename[1024-1] = '\0'; - remove(szFilename); + snprintf(filename, 1024, "%s%i", g_pOptions->GetQueueDir(), completedFile->GetID()); + filename[1024-1] = '\0'; + remove(filename); - snprintf(szFilename, 1024, "%s%is", g_pOptions->GetQueueDir(), pCompletedFile->GetID()); - szFilename[1024-1] = '\0'; - remove(szFilename); + snprintf(filename, 1024, "%s%is", g_pOptions->GetQueueDir(), completedFile->GetID()); + filename[1024-1] = '\0'; + remove(filename); - snprintf(szFilename, 1024, "%s%ic", g_pOptions->GetQueueDir(), pCompletedFile->GetID()); - szFilename[1024-1] = '\0'; - remove(szFilename); + snprintf(filename, 1024, "%s%ic", g_pOptions->GetQueueDir(), completedFile->GetID()); + filename[1024-1] = '\0'; + remove(filename); } } - snprintf(szFilename, 1024, "%sn%i.log", g_pOptions->GetQueueDir(), pNZBInfo->GetID()); - szFilename[1024-1] = '\0'; - remove(szFilename); + snprintf(filename, 1024, "%sn%i.log", g_pOptions->GetQueueDir(), nzbInfo->GetID()); + filename[1024-1] = '\0'; + remove(filename); } -bool DiskState::LoadPostQueue12(DownloadQueue* pDownloadQueue, NZBList* pNZBList, FILE* infile, int iFormatVersion) +bool DiskState::LoadPostQueue12(DownloadQueue* downloadQueue, NZBList* nzbList, FILE* infile, int formatVersion) { debug("Loading post-queue from disk"); @@ -1531,51 +1531,51 @@ bool DiskState::LoadPostQueue12(DownloadQueue* pDownloadQueue, NZBList* pNZBList if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - PostInfo* pPostInfo = NULL; - int iNZBID = 0; - unsigned int iNZBIndex = 0, iStage, iDummy; - if (iFormatVersion < 19) + PostInfo* postInfo = NULL; + int nzbId = 0; + unsigned int nzbIndex = 0, stage, dummy; + if (formatVersion < 19) { - if (fscanf(infile, "%i,%i,%i,%i\n", &iNZBIndex, &iDummy, &iDummy, &iStage) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &nzbIndex, &dummy, &dummy, &stage) != 4) goto error; } - else if (iFormatVersion < 22) + else if (formatVersion < 22) { - if (fscanf(infile, "%i,%i,%i,%i\n", &iNZBIndex, &iDummy, &iDummy, &iStage) != 4) goto error; + if (fscanf(infile, "%i,%i,%i,%i\n", &nzbIndex, &dummy, &dummy, &stage) != 4) goto error; } - else if (iFormatVersion < 43) + else if (formatVersion < 43) { - if (fscanf(infile, "%i,%i\n", &iNZBIndex, &iStage) != 2) goto error; + if (fscanf(infile, "%i,%i\n", &nzbIndex, &stage) != 2) goto error; } else { - if (fscanf(infile, "%i,%i\n", &iNZBID, &iStage) != 2) goto error; + if (fscanf(infile, "%i,%i\n", &nzbId, &stage) != 2) goto error; } - if (iFormatVersion < 18 && iStage > (int)PostInfo::ptVerifyingRepaired) iStage++; - if (iFormatVersion < 21 && iStage > (int)PostInfo::ptVerifyingRepaired) iStage++; - if (iFormatVersion < 20 && iStage > (int)PostInfo::ptUnpacking) iStage++; + if (formatVersion < 18 && stage > (int)PostInfo::ptVerifyingRepaired) stage++; + if (formatVersion < 21 && stage > (int)PostInfo::ptVerifyingRepaired) stage++; + if (formatVersion < 20 && stage > (int)PostInfo::ptUnpacking) stage++; - NZBInfo* pNZBInfo = NULL; + NZBInfo* nzbInfo = NULL; - if (iFormatVersion < 43) + if (formatVersion < 43) { - pNZBInfo = pNZBList->at(iNZBIndex - 1); - if (!pNZBInfo) goto error; + nzbInfo = nzbList->at(nzbIndex - 1); + if (!nzbInfo) goto error; } else { - pNZBInfo = FindNZBInfo(pDownloadQueue, iNZBID); - if (!pNZBInfo) goto error; + nzbInfo = FindNZBInfo(downloadQueue, nzbId); + if (!nzbInfo) goto error; } - pNZBInfo->EnterPostProcess(); - pPostInfo = pNZBInfo->GetPostInfo(); + nzbInfo->EnterPostProcess(); + postInfo = nzbInfo->GetPostInfo(); - pPostInfo->SetStage((PostInfo::EStage)iStage); + postInfo->SetStage((PostInfo::EStage)stage); // InfoName, ignore if (!fgets(buf, sizeof(buf), infile)) goto error; - if (iFormatVersion < 22) + if (formatVersion < 22) { // ParFilename, ignore if (!fgets(buf, sizeof(buf), infile)) goto error; @@ -1593,7 +1593,7 @@ error: * Loads post-queue created with older versions of nzbget. * Returns true if successful, false if not */ -bool DiskState::LoadPostQueue5(DownloadQueue* pDownloadQueue, NZBList* pNZBList) +bool DiskState::LoadPostQueue5(DownloadQueue* downloadQueue, NZBList* nzbList) { debug("Loading post-queue from disk"); @@ -1616,8 +1616,8 @@ bool DiskState::LoadPostQueue5(DownloadQueue* pDownloadQueue, NZBList* pNZBList) char FileSignatur[128]; fgets(FileSignatur, sizeof(FileSignatur), infile); - int iFormatVersion = ParseFormatVersion(FileSignatur); - if (iFormatVersion < 3 || iFormatVersion > 7) + int formatVersion = ParseFormatVersion(FileSignatur); + if (formatVersion < 3 || formatVersion > 7) { error("Could not load diskstate due to file version mismatch"); fclose(infile); @@ -1626,7 +1626,7 @@ bool DiskState::LoadPostQueue5(DownloadQueue* pDownloadQueue, NZBList* pNZBList) int size; char buf[10240]; - int iIntValue; + int intValue; // load file-infos if (fscanf(infile, "%i\n", &size) != 1) goto error; @@ -1636,33 +1636,33 @@ bool DiskState::LoadPostQueue5(DownloadQueue* pDownloadQueue, NZBList* pNZBList) if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' // find NZBInfo based on NZBFilename - NZBInfo* pNZBInfo = NULL; - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + NZBInfo* nzbInfo = NULL; + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo2 = *it; - if (!strcmp(pNZBInfo2->GetFilename(), buf)) + NZBInfo* nzbInfo2 = *it; + if (!strcmp(nzbInfo2->GetFilename(), buf)) { - pNZBInfo = pNZBInfo2; + nzbInfo = nzbInfo2; break; } } - bool bNewNZBInfo = !pNZBInfo; - if (bNewNZBInfo) + bool newNzbInfo = !nzbInfo; + if (newNzbInfo) { - pNZBInfo = new NZBInfo(); - pNZBList->push_front(pNZBInfo); - pNZBInfo->SetFilename(buf); + nzbInfo = new NZBInfo(); + nzbList->push_front(nzbInfo); + nzbInfo->SetFilename(buf); } - pNZBInfo->EnterPostProcess(); - PostInfo* pPostInfo = pNZBInfo->GetPostInfo(); + nzbInfo->EnterPostProcess(); + PostInfo* postInfo = nzbInfo->GetPostInfo(); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (bNewNZBInfo) + if (newNzbInfo) { - pNZBInfo->SetDestDir(buf); + nzbInfo->SetDestDir(buf); } // ParFilename, ignore @@ -1671,72 +1671,72 @@ bool DiskState::LoadPostQueue5(DownloadQueue* pDownloadQueue, NZBList* pNZBList) // InfoName, ignore if (!fgets(buf, sizeof(buf), infile)) goto error; - if (iFormatVersion >= 4) + if (formatVersion >= 4) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (bNewNZBInfo) + if (newNzbInfo) { - pNZBInfo->SetCategory(buf); + nzbInfo->SetCategory(buf); } } else { - if (bNewNZBInfo) + if (newNzbInfo) { - pNZBInfo->SetCategory(""); + nzbInfo->SetCategory(""); } } - if (iFormatVersion >= 5) + if (formatVersion >= 5) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (bNewNZBInfo) + if (newNzbInfo) { - pNZBInfo->SetQueuedFilename(buf); + nzbInfo->SetQueuedFilename(buf); } } else { - if (bNewNZBInfo) + if (newNzbInfo) { - pNZBInfo->SetQueuedFilename(""); + nzbInfo->SetQueuedFilename(""); } } - int iParCheck; - if (fscanf(infile, "%i\n", &iParCheck) != 1) goto error; // ParCheck + int parCheck; + if (fscanf(infile, "%i\n", &parCheck) != 1) goto error; // ParCheck - if (fscanf(infile, "%i\n", &iIntValue) != 1) goto error; - pNZBInfo->SetParStatus(iParCheck ? (NZBInfo::EParStatus)iIntValue : NZBInfo::psSkipped); + if (fscanf(infile, "%i\n", &intValue) != 1) goto error; + nzbInfo->SetParStatus(parCheck ? (NZBInfo::EParStatus)intValue : NZBInfo::psSkipped); - if (iFormatVersion < 7) + if (formatVersion < 7) { // skip old field ParFailed, not used anymore - if (fscanf(infile, "%i\n", &iIntValue) != 1) goto error; + if (fscanf(infile, "%i\n", &intValue) != 1) goto error; } - if (fscanf(infile, "%i\n", &iIntValue) != 1) goto error; - pPostInfo->SetStage((PostInfo::EStage)iIntValue); + if (fscanf(infile, "%i\n", &intValue) != 1) goto error; + postInfo->SetStage((PostInfo::EStage)intValue); - if (iFormatVersion >= 6) + if (formatVersion >= 6) { - int iParameterCount; - if (fscanf(infile, "%i\n", &iParameterCount) != 1) goto error; - for (int i = 0; i < iParameterCount; i++) + int parameterCount; + if (fscanf(infile, "%i\n", ¶meterCount) != 1) goto error; + for (int i = 0; i < parameterCount; i++) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - char* szValue = strchr(buf, '='); - if (szValue) + char* value = strchr(buf, '='); + if (value) { - *szValue = '\0'; - szValue++; - if (bNewNZBInfo) + *value = '\0'; + value++; + if (newNzbInfo) { - pNZBInfo->GetParameters()->SetParameter(buf, szValue); + nzbInfo->GetParameters()->SetParameter(buf, value); } } } @@ -1752,7 +1752,7 @@ error: return false; } -bool DiskState::LoadUrlQueue12(DownloadQueue* pDownloadQueue, FILE* infile, int iFormatVersion) +bool DiskState::LoadUrlQueue12(DownloadQueue* downloadQueue, FILE* infile, int formatVersion) { debug("Loading url-queue from disk"); int size; @@ -1762,9 +1762,9 @@ bool DiskState::LoadUrlQueue12(DownloadQueue* pDownloadQueue, FILE* infile, int for (int i = 0; i < size; i++) { - NZBInfo* pNZBInfo = new NZBInfo(); - if (!LoadUrlInfo12(pNZBInfo, infile, iFormatVersion)) goto error; - pDownloadQueue->GetQueue()->push_back(pNZBInfo); + NZBInfo* nzbInfo = new NZBInfo(); + if (!LoadUrlInfo12(nzbInfo, infile, formatVersion)) goto error; + downloadQueue->GetQueue()->push_back(nzbInfo); } return true; @@ -1774,51 +1774,51 @@ error: return false; } -bool DiskState::LoadUrlInfo12(NZBInfo* pNZBInfo, FILE* infile, int iFormatVersion) +bool DiskState::LoadUrlInfo12(NZBInfo* nzbInfo, FILE* infile, int formatVersion) { char buf[10240]; - if (iFormatVersion >= 24) + if (formatVersion >= 24) { - int iID; - if (fscanf(infile, "%i\n", &iID) != 1) goto error; - pNZBInfo->SetID(iID); + int id; + if (fscanf(infile, "%i\n", &id) != 1) goto error; + nzbInfo->SetID(id); } - int iStatusDummy, iPriority; - if (fscanf(infile, "%i,%i\n", &iStatusDummy, &iPriority) != 2) goto error; - pNZBInfo->SetPriority(iPriority); + int statusDummy, priority; + if (fscanf(infile, "%i,%i\n", &statusDummy, &priority) != 2) goto error; + nzbInfo->SetPriority(priority); - if (iFormatVersion >= 16) + if (formatVersion >= 16) { - int iAddTopDummy, iAddPaused; - if (fscanf(infile, "%i,%i\n", &iAddTopDummy, &iAddPaused) != 2) goto error; - pNZBInfo->SetAddUrlPaused(iAddPaused); + int addTopDummy, addPaused; + if (fscanf(infile, "%i,%i\n", &addTopDummy, &addPaused) != 2) goto error; + nzbInfo->SetAddUrlPaused(addPaused); } if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetURL(buf); + nzbInfo->SetURL(buf); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetFilename(buf); + nzbInfo->SetFilename(buf); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pNZBInfo->SetCategory(buf); + nzbInfo->SetCategory(buf); - if (iFormatVersion >= 31) + if (formatVersion >= 31) { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (iFormatVersion < 36) ConvertDupeKey(buf, sizeof(buf)); - pNZBInfo->SetDupeKey(buf); + if (formatVersion < 36) ConvertDupeKey(buf, sizeof(buf)); + nzbInfo->SetDupeKey(buf); - int iDupeMode, iDupeScore; - if (fscanf(infile, "%i,%i\n", &iDupeMode, &iDupeScore) != 2) goto error; - pNZBInfo->SetDupeMode((EDupeMode)iDupeMode); - pNZBInfo->SetDupeScore(iDupeScore); + int dupeMode, dupeScore; + if (fscanf(infile, "%i,%i\n", &dupeMode, &dupeScore) != 2) goto error; + nzbInfo->SetDupeMode((EDupeMode)dupeMode); + nzbInfo->SetDupeScore(dupeScore); } return true; @@ -1827,62 +1827,62 @@ error: return false; } -void DiskState::SaveDupInfo(DupInfo* pDupInfo, FILE* outfile) +void DiskState::SaveDupInfo(DupInfo* dupInfo, FILE* outfile) { unsigned long High, Low; - Util::SplitInt64(pDupInfo->GetSize(), &High, &Low); - fprintf(outfile, "%i,%lu,%lu,%u,%u,%i,%i\n", (int)pDupInfo->GetStatus(), High, Low, - pDupInfo->GetFullContentHash(), pDupInfo->GetFilteredContentHash(), - pDupInfo->GetDupeScore(), (int)pDupInfo->GetDupeMode()); - fprintf(outfile, "%s\n", pDupInfo->GetName()); - fprintf(outfile, "%s\n", pDupInfo->GetDupeKey()); + Util::SplitInt64(dupInfo->GetSize(), &High, &Low); + fprintf(outfile, "%i,%lu,%lu,%u,%u,%i,%i\n", (int)dupInfo->GetStatus(), High, Low, + dupInfo->GetFullContentHash(), dupInfo->GetFilteredContentHash(), + dupInfo->GetDupeScore(), (int)dupInfo->GetDupeMode()); + fprintf(outfile, "%s\n", dupInfo->GetName()); + fprintf(outfile, "%s\n", dupInfo->GetDupeKey()); } -bool DiskState::LoadDupInfo(DupInfo* pDupInfo, FILE* infile, int iFormatVersion) +bool DiskState::LoadDupInfo(DupInfo* dupInfo, FILE* infile, int formatVersion) { char buf[1024]; - int iStatus; + int status; unsigned long High, Low; - unsigned int iFullContentHash, iFilteredContentHash = 0; - int iDupeScore, iDupe = 0, iDupeMode = 0; + unsigned int fullContentHash, filteredContentHash = 0; + int dupeScore, dupe = 0, dupeMode = 0; - if (iFormatVersion >= 39) + if (formatVersion >= 39) { - if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i,%i\n", &iStatus, &High, &Low, &iFullContentHash, &iFilteredContentHash, &iDupeScore, &iDupeMode) != 7) goto error; + if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i,%i\n", &status, &High, &Low, &fullContentHash, &filteredContentHash, &dupeScore, &dupeMode) != 7) goto error; } - else if (iFormatVersion >= 38) + else if (formatVersion >= 38) { - if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i,%i,%i\n", &iStatus, &High, &Low, &iFullContentHash, &iFilteredContentHash, &iDupeScore, &iDupe, &iDupeMode) != 8) goto error; + if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i,%i,%i\n", &status, &High, &Low, &fullContentHash, &filteredContentHash, &dupeScore, &dupe, &dupeMode) != 8) goto error; } - else if (iFormatVersion >= 37) + else if (formatVersion >= 37) { - if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i,%i\n", &iStatus, &High, &Low, &iFullContentHash, &iFilteredContentHash, &iDupeScore, &iDupe) != 7) goto error; + if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i,%i\n", &status, &High, &Low, &fullContentHash, &filteredContentHash, &dupeScore, &dupe) != 7) goto error; } - else if (iFormatVersion >= 34) + else if (formatVersion >= 34) { - if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i\n", &iStatus, &High, &Low, &iFullContentHash, &iFilteredContentHash, &iDupeScore) != 6) goto error; + if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i\n", &status, &High, &Low, &fullContentHash, &filteredContentHash, &dupeScore) != 6) goto error; } else { - if (fscanf(infile, "%i,%lu,%lu,%u,%i\n", &iStatus, &High, &Low, &iFullContentHash, &iDupeScore) != 5) goto error; + if (fscanf(infile, "%i,%lu,%lu,%u,%i\n", &status, &High, &Low, &fullContentHash, &dupeScore) != 5) goto error; } - pDupInfo->SetStatus((DupInfo::EStatus)iStatus); - pDupInfo->SetFullContentHash(iFullContentHash); - pDupInfo->SetFilteredContentHash(iFilteredContentHash); - pDupInfo->SetSize(Util::JoinInt64(High, Low)); - pDupInfo->SetDupeScore(iDupeScore); - pDupInfo->SetDupeMode((EDupeMode)iDupeMode); + dupInfo->SetStatus((DupInfo::EStatus)status); + dupInfo->SetFullContentHash(fullContentHash); + dupInfo->SetFilteredContentHash(filteredContentHash); + dupInfo->SetSize(Util::JoinInt64(High, Low)); + dupInfo->SetDupeScore(dupeScore); + dupInfo->SetDupeMode((EDupeMode)dupeMode); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - pDupInfo->SetName(buf); + dupInfo->SetName(buf); if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - if (iFormatVersion < 36) ConvertDupeKey(buf, sizeof(buf)); - pDupInfo->SetDupeKey(buf); + if (formatVersion < 36) ConvertDupeKey(buf, sizeof(buf)); + dupInfo->SetDupeKey(buf); return true; @@ -1890,29 +1890,29 @@ error: return false; } -void DiskState::SaveHistory(DownloadQueue* pDownloadQueue, FILE* outfile) +void DiskState::SaveHistory(DownloadQueue* downloadQueue, FILE* outfile) { debug("Saving history to disk"); - fprintf(outfile, "%i\n", (int)pDownloadQueue->GetHistory()->size()); - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + fprintf(outfile, "%i\n", (int)downloadQueue->GetHistory()->size()); + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; + HistoryInfo* historyInfo = *it; - fprintf(outfile, "%i,%i,%i\n", pHistoryInfo->GetID(), (int)pHistoryInfo->GetKind(), (int)pHistoryInfo->GetTime()); + fprintf(outfile, "%i,%i,%i\n", historyInfo->GetID(), (int)historyInfo->GetKind(), (int)historyInfo->GetTime()); - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb || pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkNzb || historyInfo->GetKind() == HistoryInfo::hkUrl) { - SaveNZBInfo(pHistoryInfo->GetNZBInfo(), outfile); + SaveNZBInfo(historyInfo->GetNZBInfo(), outfile); } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkDup) + else if (historyInfo->GetKind() == HistoryInfo::hkDup) { - SaveDupInfo(pHistoryInfo->GetDupInfo(), outfile); + SaveDupInfo(historyInfo->GetDupInfo(), outfile); } } } -bool DiskState::LoadHistory(DownloadQueue* pDownloadQueue, NZBList* pNZBList, Servers* pServers, FILE* infile, int iFormatVersion) +bool DiskState::LoadHistory(DownloadQueue* downloadQueue, NZBList* nzbList, Servers* servers, FILE* infile, int formatVersion) { debug("Loading history from disk"); @@ -1920,89 +1920,89 @@ bool DiskState::LoadHistory(DownloadQueue* pDownloadQueue, NZBList* pNZBList, Se if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - HistoryInfo* pHistoryInfo = NULL; - HistoryInfo::EKind eKind = HistoryInfo::hkNzb; - int iID = 0; - int iTime; + HistoryInfo* historyInfo = NULL; + HistoryInfo::EKind kind = HistoryInfo::hkNzb; + int id = 0; + int time; - if (iFormatVersion >= 33) + if (formatVersion >= 33) { - int iKind = 0; - if (fscanf(infile, "%i,%i,%i\n", &iID, &iKind, &iTime) != 3) goto error; - eKind = (HistoryInfo::EKind)iKind; + int kindval = 0; + if (fscanf(infile, "%i,%i,%i\n", &id, &kindval, &time) != 3) goto error; + kind = (HistoryInfo::EKind)kindval; } else { - if (iFormatVersion >= 24) + if (formatVersion >= 24) { - if (fscanf(infile, "%i\n", &iID) != 1) goto error; + if (fscanf(infile, "%i\n", &id) != 1) goto error; } - if (iFormatVersion >= 15) + if (formatVersion >= 15) { - int iKind = 0; - if (fscanf(infile, "%i\n", &iKind) != 1) goto error; - eKind = (HistoryInfo::EKind)iKind; + int kindval = 0; + if (fscanf(infile, "%i\n", &kindval) != 1) goto error; + kind = (HistoryInfo::EKind)kindval; } } - if (eKind == HistoryInfo::hkNzb) + if (kind == HistoryInfo::hkNzb) { - NZBInfo* pNZBInfo = NULL; + NZBInfo* nzbInfo = NULL; - if (iFormatVersion < 43) + if (formatVersion < 43) { - unsigned int iNZBIndex; - if (fscanf(infile, "%i\n", &iNZBIndex) != 1) goto error; - pNZBInfo = pNZBList->at(iNZBIndex - 1); + unsigned int nzbIndex; + if (fscanf(infile, "%i\n", &nzbIndex) != 1) goto error; + nzbInfo = nzbList->at(nzbIndex - 1); } else { - pNZBInfo = new NZBInfo(); - if (!LoadNZBInfo(pNZBInfo, pServers, infile, iFormatVersion)) goto error; - pNZBInfo->LeavePostProcess(); + nzbInfo = new NZBInfo(); + if (!LoadNZBInfo(nzbInfo, servers, infile, formatVersion)) goto error; + nzbInfo->LeavePostProcess(); } - pHistoryInfo = new HistoryInfo(pNZBInfo); + historyInfo = new HistoryInfo(nzbInfo); - if (iFormatVersion < 28 && pNZBInfo->GetParStatus() == 0 && - pNZBInfo->GetUnpackStatus() == 0 && pNZBInfo->GetMoveStatus() == 0) + if (formatVersion < 28 && nzbInfo->GetParStatus() == 0 && + nzbInfo->GetUnpackStatus() == 0 && nzbInfo->GetMoveStatus() == 0) { - pNZBInfo->SetDeleteStatus(NZBInfo::dsManual); + nzbInfo->SetDeleteStatus(NZBInfo::dsManual); } } - else if (eKind == HistoryInfo::hkUrl) + else if (kind == HistoryInfo::hkUrl) { - NZBInfo* pNZBInfo = new NZBInfo(); - if (iFormatVersion >= 46) + NZBInfo* nzbInfo = new NZBInfo(); + if (formatVersion >= 46) { - if (!LoadNZBInfo(pNZBInfo, pServers, infile, iFormatVersion)) goto error; + if (!LoadNZBInfo(nzbInfo, servers, infile, formatVersion)) goto error; } else { - if (!LoadUrlInfo12(pNZBInfo, infile, iFormatVersion)) goto error; + if (!LoadUrlInfo12(nzbInfo, infile, formatVersion)) goto error; } - pHistoryInfo = new HistoryInfo(pNZBInfo); + historyInfo = new HistoryInfo(nzbInfo); } - else if (eKind == HistoryInfo::hkDup) + else if (kind == HistoryInfo::hkDup) { - DupInfo* pDupInfo = new DupInfo(); - if (!LoadDupInfo(pDupInfo, infile, iFormatVersion)) goto error; - if (iFormatVersion >= 47) + DupInfo* dupInfo = new DupInfo(); + if (!LoadDupInfo(dupInfo, infile, formatVersion)) goto error; + if (formatVersion >= 47) { - pDupInfo->SetID(iID); + dupInfo->SetID(id); } - pHistoryInfo = new HistoryInfo(pDupInfo); + historyInfo = new HistoryInfo(dupInfo); } - if (iFormatVersion < 33) + if (formatVersion < 33) { - if (fscanf(infile, "%i\n", &iTime) != 1) goto error; + if (fscanf(infile, "%i\n", &time) != 1) goto error; } - pHistoryInfo->SetTime((time_t)iTime); + historyInfo->SetTime((time_t)time); - pDownloadQueue->GetHistory()->push_back(pHistoryInfo); + downloadQueue->GetHistory()->push_back(historyInfo); } return true; @@ -2015,32 +2015,32 @@ error: /* * Find index of nzb-info. */ -int DiskState::FindNZBInfoIndex(NZBList* pNZBList, NZBInfo* pNZBInfo) +int DiskState::FindNZBInfoIndex(NZBList* nzbList, NZBInfo* nzbInfo) { - int iNZBIndex = 0; - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + int nzbIndex = 0; + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo2 = *it; - iNZBIndex++; - if (pNZBInfo2 == pNZBInfo) + NZBInfo* nzbInfo2 = *it; + nzbIndex++; + if (nzbInfo2 == nzbInfo) { break; } } - return iNZBIndex; + return nzbIndex; } /* * Find nzb-info by id. */ -NZBInfo* DiskState::FindNZBInfo(DownloadQueue* pDownloadQueue, int iID) +NZBInfo* DiskState::FindNZBInfo(DownloadQueue* downloadQueue, int id) { - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - if (pNZBInfo->GetID() == iID) + NZBInfo* nzbInfo = *it; + if (nzbInfo->GetID() == id) { - return pNZBInfo; + return nzbInfo; } } return NULL; @@ -2053,39 +2053,39 @@ void DiskState::DiscardDownloadQueue() { debug("Discarding queue"); - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "queue"); - szFullFilename[1024-1] = '\0'; - remove(szFullFilename); + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "queue"); + fullFilename[1024-1] = '\0'; + remove(fullFilename); DirBrowser dir(g_pOptions->GetQueueDir()); while (const char* filename = dir.Next()) { // delete all files whose names have only characters '0'..'9' - bool bOnlyNums = true; + bool onlyNums = true; for (const char* p = filename; *p != '\0'; p++) { if (!('0' <= *p && *p <= '9')) { - bOnlyNums = false; + onlyNums = false; break; } } - if (bOnlyNums) + if (onlyNums) { - snprintf(szFullFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), filename); - szFullFilename[1024-1] = '\0'; - remove(szFullFilename); + snprintf(fullFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), filename); + fullFilename[1024-1] = '\0'; + remove(fullFilename); // delete file state file - snprintf(szFullFilename, 1024, "%s%ss", g_pOptions->GetQueueDir(), filename); - szFullFilename[1024-1] = '\0'; - remove(szFullFilename); + snprintf(fullFilename, 1024, "%s%ss", g_pOptions->GetQueueDir(), filename); + fullFilename[1024-1] = '\0'; + remove(fullFilename); // delete failed info file - snprintf(szFullFilename, 1024, "%s%sc", g_pOptions->GetQueueDir(), filename); - szFullFilename[1024-1] = '\0'; - remove(szFullFilename); + snprintf(fullFilename, 1024, "%s%sc", g_pOptions->GetQueueDir(), filename); + fullFilename[1024-1] = '\0'; + remove(fullFilename); } } } @@ -2100,36 +2100,36 @@ bool DiskState::DownloadQueueExists() return Util::FileExists(fileName); } -void DiskState::DiscardFile(FileInfo* pFileInfo, bool bDeleteData, bool bDeletePartialState, bool bDeleteCompletedState) +void DiskState::DiscardFile(FileInfo* fileInfo, bool deleteData, bool deletePartialState, bool deleteCompletedState) { char fileName[1024]; // info and articles file - if (bDeleteData) + if (deleteData) { - snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), pFileInfo->GetID()); + snprintf(fileName, 1024, "%s%i", g_pOptions->GetQueueDir(), fileInfo->GetID()); fileName[1024-1] = '\0'; remove(fileName); } // partial state file - if (bDeletePartialState) + if (deletePartialState) { - snprintf(fileName, 1024, "%s%is", g_pOptions->GetQueueDir(), pFileInfo->GetID()); + snprintf(fileName, 1024, "%s%is", g_pOptions->GetQueueDir(), fileInfo->GetID()); fileName[1024-1] = '\0'; remove(fileName); } // completed state file - if (bDeleteCompletedState) + if (deleteCompletedState) { - snprintf(fileName, 1024, "%s%ic", g_pOptions->GetQueueDir(), pFileInfo->GetID()); + snprintf(fileName, 1024, "%s%ic", g_pOptions->GetQueueDir(), fileInfo->GetID()); fileName[1024-1] = '\0'; remove(fileName); } } -void DiskState::CleanupTempDir(DownloadQueue* pDownloadQueue) +void DiskState::CleanupTempDir(DownloadQueue* downloadQueue) { DirBrowser dir(g_pOptions->GetTempDir()); while (const char* filename = dir.Next()) @@ -2138,10 +2138,10 @@ void DiskState::CleanupTempDir(DownloadQueue* pDownloadQueue) if (strstr(filename, ".tmp") || strstr(filename, ".dec") || (sscanf(filename, "%i.%i", &id, &part) == 2)) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%s", g_pOptions->GetTempDir(), filename); - szFullFilename[1024-1] = '\0'; - remove(szFullFilename); + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%s", g_pOptions->GetTempDir(), filename); + fullFilename[1024-1] = '\0'; + remove(fullFilename); } } } @@ -2151,13 +2151,13 @@ void DiskState::CleanupTempDir(DownloadQueue* pDownloadQueue) * - then delete feeds * - then rename feeds.new to feeds */ -bool DiskState::SaveFeeds(Feeds* pFeeds, FeedHistory* pFeedHistory) +bool DiskState::SaveFeeds(Feeds* feeds, FeedHistory* feedHistory) { debug("Saving feeds state to disk"); StateFile stateFile("feeds", 3); - if (pFeeds->empty() && pFeedHistory->empty()) + if (feeds->empty() && feedHistory->empty()) { stateFile.Discard(); return true; @@ -2170,16 +2170,16 @@ bool DiskState::SaveFeeds(Feeds* pFeeds, FeedHistory* pFeedHistory) } // save status - SaveFeedStatus(pFeeds, outfile); + SaveFeedStatus(feeds, outfile); // save history - SaveFeedHistory(pFeedHistory, outfile); + SaveFeedHistory(feedHistory, outfile); // now rename to dest file name return stateFile.FinishWriteTransaction(); } -bool DiskState::LoadFeeds(Feeds* pFeeds, FeedHistory* pFeedHistory) +bool DiskState::LoadFeeds(Feeds* feeds, FeedHistory* feedHistory) { debug("Loading feeds state from disk"); @@ -2196,45 +2196,45 @@ bool DiskState::LoadFeeds(Feeds* pFeeds, FeedHistory* pFeedHistory) return false; } - bool bOK = false; - int iFormatVersion = stateFile.GetFileVersion(); + bool ok = false; + int formatVersion = stateFile.GetFileVersion(); // load feed status - if (!LoadFeedStatus(pFeeds, infile, iFormatVersion)) goto error; + if (!LoadFeedStatus(feeds, infile, formatVersion)) goto error; // load feed history - if (!LoadFeedHistory(pFeedHistory, infile, iFormatVersion)) goto error; + if (!LoadFeedHistory(feedHistory, infile, formatVersion)) goto error; - bOK = true; + ok = true; error: - if (!bOK) + if (!ok) { error("Error reading diskstate for feeds"); } - return bOK; + return ok; } -bool DiskState::SaveFeedStatus(Feeds* pFeeds, FILE* outfile) +bool DiskState::SaveFeedStatus(Feeds* feeds, FILE* outfile) { debug("Saving feed status to disk"); - fprintf(outfile, "%i\n", (int)pFeeds->size()); - for (Feeds::iterator it = pFeeds->begin(); it != pFeeds->end(); it++) + fprintf(outfile, "%i\n", (int)feeds->size()); + for (Feeds::iterator it = feeds->begin(); it != feeds->end(); it++) { - FeedInfo* pFeedInfo = *it; + FeedInfo* feedInfo = *it; - fprintf(outfile, "%s\n", pFeedInfo->GetUrl()); - fprintf(outfile, "%u\n", pFeedInfo->GetFilterHash()); - fprintf(outfile, "%i\n", (int)pFeedInfo->GetLastUpdate()); + fprintf(outfile, "%s\n", feedInfo->GetUrl()); + fprintf(outfile, "%u\n", feedInfo->GetFilterHash()); + fprintf(outfile, "%i\n", (int)feedInfo->GetLastUpdate()); } return true; } -bool DiskState::LoadFeedStatus(Feeds* pFeeds, FILE* infile, int iFormatVersion) +bool DiskState::LoadFeedStatus(Feeds* feeds, FILE* infile, int formatVersion) { debug("Loading feed status from disk"); @@ -2242,36 +2242,36 @@ bool DiskState::LoadFeedStatus(Feeds* pFeeds, FILE* infile, int iFormatVersion) if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - char szUrl[1024]; - if (!fgets(szUrl, sizeof(szUrl), infile)) goto error; - if (szUrl[0] != 0) szUrl[strlen(szUrl)-1] = 0; // remove traling '\n' + char url[1024]; + if (!fgets(url, sizeof(url), infile)) goto error; + if (url[0] != 0) url[strlen(url)-1] = 0; // remove traling '\n' - char szFilter[1024]; - if (iFormatVersion == 2) + char filter[1024]; + if (formatVersion == 2) { - if (!fgets(szFilter, sizeof(szFilter), infile)) goto error; - if (szFilter[0] != 0) szFilter[strlen(szFilter)-1] = 0; // remove traling '\n' + if (!fgets(filter, sizeof(filter), infile)) goto error; + if (filter[0] != 0) filter[strlen(filter)-1] = 0; // remove traling '\n' } - unsigned int iFilterHash = 0; - if (iFormatVersion >= 3) + unsigned int filterHash = 0; + if (formatVersion >= 3) { - if (fscanf(infile, "%u\n", &iFilterHash) != 1) goto error; + if (fscanf(infile, "%u\n", &filterHash) != 1) goto error; } - int iLastUpdate = 0; - if (fscanf(infile, "%i\n", &iLastUpdate) != 1) goto error; + int lastUpdate = 0; + if (fscanf(infile, "%i\n", &lastUpdate) != 1) goto error; - for (Feeds::iterator it = pFeeds->begin(); it != pFeeds->end(); it++) + for (Feeds::iterator it = feeds->begin(); it != feeds->end(); it++) { - FeedInfo* pFeedInfo = *it; + FeedInfo* feedInfo = *it; - if (!strcmp(pFeedInfo->GetUrl(), szUrl) && - ((iFormatVersion == 1) || - (iFormatVersion == 2 && !strcmp(pFeedInfo->GetFilter(), szFilter)) || - (iFormatVersion >= 3 && pFeedInfo->GetFilterHash() == iFilterHash))) + if (!strcmp(feedInfo->GetUrl(), url) && + ((formatVersion == 1) || + (formatVersion == 2 && !strcmp(feedInfo->GetFilter(), filter)) || + (formatVersion >= 3 && feedInfo->GetFilterHash() == filterHash))) { - pFeedInfo->SetLastUpdate((time_t)iLastUpdate); + feedInfo->SetLastUpdate((time_t)lastUpdate); } } } @@ -2283,23 +2283,23 @@ error: return false; } -bool DiskState::SaveFeedHistory(FeedHistory* pFeedHistory, FILE* outfile) +bool DiskState::SaveFeedHistory(FeedHistory* feedHistory, FILE* outfile) { debug("Saving feed history to disk"); - fprintf(outfile, "%i\n", (int)pFeedHistory->size()); - for (FeedHistory::iterator it = pFeedHistory->begin(); it != pFeedHistory->end(); it++) + fprintf(outfile, "%i\n", (int)feedHistory->size()); + for (FeedHistory::iterator it = feedHistory->begin(); it != feedHistory->end(); it++) { - FeedHistoryInfo* pFeedHistoryInfo = *it; + FeedHistoryInfo* feedHistoryInfo = *it; - fprintf(outfile, "%i,%i\n", (int)pFeedHistoryInfo->GetStatus(), (int)pFeedHistoryInfo->GetLastSeen()); - fprintf(outfile, "%s\n", pFeedHistoryInfo->GetUrl()); + fprintf(outfile, "%i,%i\n", (int)feedHistoryInfo->GetStatus(), (int)feedHistoryInfo->GetLastSeen()); + fprintf(outfile, "%s\n", feedHistoryInfo->GetUrl()); } return true; } -bool DiskState::LoadFeedHistory(FeedHistory* pFeedHistory, FILE* infile, int iFormatVersion) +bool DiskState::LoadFeedHistory(FeedHistory* feedHistory, FILE* infile, int formatVersion) { debug("Loading feed history from disk"); @@ -2307,16 +2307,16 @@ bool DiskState::LoadFeedHistory(FeedHistory* pFeedHistory, FILE* infile, int iFo if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - int iStatus = 0; - int iLastSeen = 0; - int r = fscanf(infile, "%i,%i\n", &iStatus, &iLastSeen); + int status = 0; + int lastSeen = 0; + int r = fscanf(infile, "%i,%i\n", &status, &lastSeen); if (r != 2) goto error; - char szUrl[1024]; - if (!fgets(szUrl, sizeof(szUrl), infile)) goto error; - if (szUrl[0] != 0) szUrl[strlen(szUrl)-1] = 0; // remove traling '\n' + char url[1024]; + if (!fgets(url, sizeof(url), infile)) goto error; + if (url[0] != 0) url[strlen(url)-1] = 0; // remove traling '\n' - pFeedHistory->Add(szUrl, (FeedHistoryInfo::EStatus)(iStatus), (time_t)(iLastSeen)); + feedHistory->Add(url, (FeedHistoryInfo::EStatus)(status), (time_t)(lastSeen)); } return true; @@ -2327,117 +2327,117 @@ error: } // calculate critical health for old NZBs -void DiskState::CalcCriticalHealth(NZBList* pNZBList) +void DiskState::CalcCriticalHealth(NZBList* nzbList) { // build list of old NZBs which do not have critical health calculated - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo = *it; - if (pNZBInfo->CalcCriticalHealth(false) == 1000) + NZBInfo* nzbInfo = *it; + if (nzbInfo->CalcCriticalHealth(false) == 1000) { - debug("Calculating critical health for %s", pNZBInfo->GetName()); + debug("Calculating critical health for %s", nzbInfo->GetName()); - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; + FileInfo* fileInfo = *it; - char szLoFileName[1024]; - strncpy(szLoFileName, pFileInfo->GetFilename(), 1024); - szLoFileName[1024-1] = '\0'; - for (char* p = szLoFileName; *p; p++) *p = tolower(*p); // convert string to lowercase - bool bParFile = strstr(szLoFileName, ".par2"); + char loFileName[1024]; + strncpy(loFileName, fileInfo->GetFilename(), 1024); + loFileName[1024-1] = '\0'; + for (char* p = loFileName; *p; p++) *p = tolower(*p); // convert string to lowercase + bool parFile = strstr(loFileName, ".par2"); - pFileInfo->SetParFile(bParFile); - if (bParFile) + fileInfo->SetParFile(parFile); + if (parFile) { - pNZBInfo->SetParSize(pNZBInfo->GetParSize() + pFileInfo->GetSize()); + nzbInfo->SetParSize(nzbInfo->GetParSize() + fileInfo->GetSize()); } } } } } -void DiskState::CalcFileStats(DownloadQueue* pDownloadQueue, int iFormatVersion) +void DiskState::CalcFileStats(DownloadQueue* downloadQueue, int formatVersion) { - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - CalcNZBFileStats(pNZBInfo, iFormatVersion); + NZBInfo* nzbInfo = *it; + CalcNZBFileStats(nzbInfo, formatVersion); } - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { - CalcNZBFileStats(pHistoryInfo->GetNZBInfo(), iFormatVersion); + CalcNZBFileStats(historyInfo->GetNZBInfo(), formatVersion); } } } -void DiskState::CalcNZBFileStats(NZBInfo* pNZBInfo, int iFormatVersion) +void DiskState::CalcNZBFileStats(NZBInfo* nzbInfo, int formatVersion) { - int iPausedFileCount = 0; - int iRemainingParCount = 0; - int iSuccessArticles = 0; - int iFailedArticles = 0; - long long lRemainingSize = 0; - long long lPausedSize = 0; - long long lSuccessSize = 0; - long long lFailedSize = 0; - long long lParSuccessSize = 0; - long long lParFailedSize = 0; + int pausedFileCount = 0; + int remainingParCount = 0; + int successArticles = 0; + int failedArticles = 0; + long long remainingSize = 0; + long long pausedSize = 0; + long long successSize = 0; + long long failedSize = 0; + long long parSuccessSize = 0; + long long parFailedSize = 0; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; + FileInfo* fileInfo = *it2; - lRemainingSize += pFileInfo->GetRemainingSize(); - iSuccessArticles += pFileInfo->GetSuccessArticles(); - iFailedArticles += pFileInfo->GetFailedArticles(); - lSuccessSize += pFileInfo->GetSuccessSize(); - lFailedSize += pFileInfo->GetFailedSize(); + remainingSize += fileInfo->GetRemainingSize(); + successArticles += fileInfo->GetSuccessArticles(); + failedArticles += fileInfo->GetFailedArticles(); + successSize += fileInfo->GetSuccessSize(); + failedSize += fileInfo->GetFailedSize(); - if (pFileInfo->GetPaused()) + if (fileInfo->GetPaused()) { - lPausedSize += pFileInfo->GetRemainingSize(); - iPausedFileCount++; + pausedSize += fileInfo->GetRemainingSize(); + pausedFileCount++; } - if (pFileInfo->GetParFile()) + if (fileInfo->GetParFile()) { - iRemainingParCount++; - lParSuccessSize += pFileInfo->GetSuccessSize(); - lParFailedSize += pFileInfo->GetFailedSize(); + remainingParCount++; + parSuccessSize += fileInfo->GetSuccessSize(); + parFailedSize += fileInfo->GetFailedSize(); } - pNZBInfo->GetCurrentServerStats()->ListOp(pFileInfo->GetServerStats(), ServerStatList::soAdd); + nzbInfo->GetCurrentServerStats()->ListOp(fileInfo->GetServerStats(), ServerStatList::soAdd); } - pNZBInfo->SetRemainingSize(lRemainingSize); - pNZBInfo->SetPausedSize(lPausedSize); - pNZBInfo->SetPausedFileCount(iPausedFileCount); - pNZBInfo->SetRemainingParCount(iRemainingParCount); + nzbInfo->SetRemainingSize(remainingSize); + nzbInfo->SetPausedSize(pausedSize); + nzbInfo->SetPausedFileCount(pausedFileCount); + nzbInfo->SetRemainingParCount(remainingParCount); - pNZBInfo->SetCurrentSuccessArticles(pNZBInfo->GetSuccessArticles() + iSuccessArticles); - pNZBInfo->SetCurrentFailedArticles(pNZBInfo->GetFailedArticles() + iFailedArticles); - pNZBInfo->SetCurrentSuccessSize(pNZBInfo->GetSuccessSize() + lSuccessSize); - pNZBInfo->SetCurrentFailedSize(pNZBInfo->GetFailedSize() + lFailedSize); - pNZBInfo->SetParCurrentSuccessSize(pNZBInfo->GetParSuccessSize() + lParSuccessSize); - pNZBInfo->SetParCurrentFailedSize(pNZBInfo->GetParFailedSize() + lParFailedSize); + nzbInfo->SetCurrentSuccessArticles(nzbInfo->GetSuccessArticles() + successArticles); + nzbInfo->SetCurrentFailedArticles(nzbInfo->GetFailedArticles() + failedArticles); + nzbInfo->SetCurrentSuccessSize(nzbInfo->GetSuccessSize() + successSize); + nzbInfo->SetCurrentFailedSize(nzbInfo->GetFailedSize() + failedSize); + nzbInfo->SetParCurrentSuccessSize(nzbInfo->GetParSuccessSize() + parSuccessSize); + nzbInfo->SetParCurrentFailedSize(nzbInfo->GetParFailedSize() + parFailedSize); - if (iFormatVersion < 44) + if (formatVersion < 44) { - pNZBInfo->UpdateMinMaxTime(); + nzbInfo->UpdateMinMaxTime(); } } -bool DiskState::LoadAllFileStates(DownloadQueue* pDownloadQueue, Servers* pServers) +bool DiskState::LoadAllFileStates(DownloadQueue* downloadQueue, Servers* servers) { - char szCacheFlagFilename[1024]; - snprintf(szCacheFlagFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "acache"); - szCacheFlagFilename[1024-1] = '\0'; + char cacheFlagFilename[1024]; + snprintf(cacheFlagFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "acache"); + cacheFlagFilename[1024-1] = '\0'; - bool bCacheWasActive = Util::FileExists(szCacheFlagFilename); + bool cacheWasActive = Util::FileExists(cacheFlagFilename); DirBrowser dir(g_pOptions->GetQueueDir()); while (const char* filename = dir.Next()) @@ -2446,28 +2446,28 @@ bool DiskState::LoadAllFileStates(DownloadQueue* pDownloadQueue, Servers* pServe char suffix; if (sscanf(filename, "%i%c", &id, &suffix) == 2 && suffix == 's') { - if (g_pOptions->GetContinuePartial() && !bCacheWasActive) + if (g_pOptions->GetContinuePartial() && !cacheWasActive) { - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - if (pFileInfo->GetID() == id) + FileInfo* fileInfo = *it2; + if (fileInfo->GetID() == id) { - if (!LoadArticles(pFileInfo)) goto error; - if (!LoadFileState(pFileInfo, pServers, false)) goto error; + if (!LoadArticles(fileInfo)) goto error; + if (!LoadFileState(fileInfo, servers, false)) goto error; } } } } else { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), filename); - szFullFilename[1024-1] = '\0'; - remove(szFullFilename); + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), filename); + fullFilename[1024-1] = '\0'; + remove(fullFilename); } } } @@ -2485,33 +2485,33 @@ void DiskState::ConvertDupeKey(char* buf, int bufsize) return; } - int iRageId = atoi(buf + 7); - int iSeason = 0; - int iEpisode = 0; + int rageId = atoi(buf + 7); + int season = 0; + int episode = 0; char* p = strchr(buf + 7, ','); if (p) { - iSeason = atoi(p + 1); + season = atoi(p + 1); p = strchr(p + 1, ','); if (p) { - iEpisode = atoi(p + 1); + episode = atoi(p + 1); } } - if (iRageId != 0 && iSeason != 0 && iEpisode != 0) + if (rageId != 0 && season != 0 && episode != 0) { - snprintf(buf, bufsize, "rageid=%i-S%02i-E%02i", iRageId, iSeason, iEpisode); + snprintf(buf, bufsize, "rageid=%i-S%02i-E%02i", rageId, season, episode); } } -bool DiskState::SaveStats(Servers* pServers, ServerVolumes* pServerVolumes) +bool DiskState::SaveStats(Servers* servers, ServerVolumes* serverVolumes) { debug("Saving stats to disk"); StateFile stateFile("stats", 3); - if (pServers->empty()) + if (servers->empty()) { stateFile.Discard(); return true; @@ -2524,16 +2524,16 @@ bool DiskState::SaveStats(Servers* pServers, ServerVolumes* pServerVolumes) } // save server names - SaveServerInfo(pServers, outfile); + SaveServerInfo(servers, outfile); // save stat - SaveVolumeStat(pServerVolumes, outfile); + SaveVolumeStat(serverVolumes, outfile); // now rename to dest file name return stateFile.FinishWriteTransaction(); } -bool DiskState::LoadStats(Servers* pServers, ServerVolumes* pServerVolumes, bool* pPerfectMatch) +bool DiskState::LoadStats(Servers* servers, ServerVolumes* serverVolumes, bool* perfectMatch) { debug("Loading stats from disk"); @@ -2550,41 +2550,41 @@ bool DiskState::LoadStats(Servers* pServers, ServerVolumes* pServerVolumes, bool return false; } - bool bOK = false; - int iFormatVersion = stateFile.GetFileVersion(); + bool ok = false; + int formatVersion = stateFile.GetFileVersion(); - if (!LoadServerInfo(pServers, infile, iFormatVersion, pPerfectMatch)) goto error; + if (!LoadServerInfo(servers, infile, formatVersion, perfectMatch)) goto error; - if (iFormatVersion >=2) + if (formatVersion >=2) { - if (!LoadVolumeStat(pServers, pServerVolumes, infile, iFormatVersion)) goto error; + if (!LoadVolumeStat(servers, serverVolumes, infile, formatVersion)) goto error; } - bOK = true; + ok = true; error: - if (!bOK) + if (!ok) { error("Error reading diskstate for statistics"); } - return bOK; + return ok; } -bool DiskState::SaveServerInfo(Servers* pServers, FILE* outfile) +bool DiskState::SaveServerInfo(Servers* servers, FILE* outfile) { debug("Saving server info to disk"); - fprintf(outfile, "%i\n", (int)pServers->size()); - for (Servers::iterator it = pServers->begin(); it != pServers->end(); it++) + fprintf(outfile, "%i\n", (int)servers->size()); + for (Servers::iterator it = servers->begin(); it != servers->end(); it++) { - NewsServer* pNewsServer = *it; + NewsServer* newsServer = *it; - fprintf(outfile, "%s\n", pNewsServer->GetName()); - fprintf(outfile, "%s\n", pNewsServer->GetHost()); - fprintf(outfile, "%i\n", pNewsServer->GetPort()); - fprintf(outfile, "%s\n", pNewsServer->GetUser()); + fprintf(outfile, "%s\n", newsServer->GetName()); + fprintf(outfile, "%s\n", newsServer->GetHost()); + fprintf(outfile, "%i\n", newsServer->GetPort()); + fprintf(outfile, "%s\n", newsServer->GetUser()); } return true; @@ -2598,139 +2598,139 @@ bool DiskState::SaveServerInfo(Servers* pServers, FILE* outfile) class ServerRef { public: - int m_iStateID; - char* m_szName; - char* m_szHost; - int m_iPort; - char* m_szUser; - bool m_bMatched; - bool m_bPerfect; + int m_stateId; + char* m_name; + char* m_host; + int m_port; + char* m_user; + bool m_matched; + bool m_perfect; ~ServerRef(); - int GetStateID() { return m_iStateID; } - const char* GetName() { return m_szName; } - const char* GetHost() { return m_szHost; } - int GetPort() { return m_iPort; } - const char* GetUser() { return m_szUser; } - bool GetMatched() { return m_bMatched; } - void SetMatched(bool bMatched) { m_bMatched = bMatched; } - bool GetPerfect() { return m_bPerfect; } - void SetPerfect(bool bPerfect) { m_bPerfect = bPerfect; } + int GetStateID() { return m_stateId; } + const char* GetName() { return m_name; } + const char* GetHost() { return m_host; } + int GetPort() { return m_port; } + const char* GetUser() { return m_user; } + bool GetMatched() { return m_matched; } + void SetMatched(bool matched) { m_matched = matched; } + bool GetPerfect() { return m_perfect; } + void SetPerfect(bool perfect) { m_perfect = perfect; } }; typedef std::deque ServerRefList; ServerRef::~ServerRef() { - free(m_szName); - free(m_szHost); - free(m_szUser); + free(m_name); + free(m_host); + free(m_user); } enum ECriteria { - eName, - eHost, - ePort, - eUser + name, + host, + port, + user }; -void FindCandidates(NewsServer* pNewsServer, ServerRefList* pRefs, ECriteria eCriteria, bool bKeepIfNothing) +void FindCandidates(NewsServer* newsServer, ServerRefList* refs, ECriteria criteria, bool keepIfNothing) { ServerRefList originalRefs; - originalRefs.insert(originalRefs.begin(), pRefs->begin(), pRefs->end()); + originalRefs.insert(originalRefs.begin(), refs->begin(), refs->end()); int index = 0; - for (ServerRefList::iterator it = pRefs->begin(); it != pRefs->end(); ) + for (ServerRefList::iterator it = refs->begin(); it != refs->end(); ) { - ServerRef* pRef = *it; - bool bMatch = false; - switch(eCriteria) + ServerRef* ref = *it; + bool match = false; + switch(criteria) { - case eName: - bMatch = !strcasecmp(pNewsServer->GetName(), pRef->GetName()); + case name: + match = !strcasecmp(newsServer->GetName(), ref->GetName()); break; - case eHost: - bMatch = !strcasecmp(pNewsServer->GetHost(), pRef->GetHost()); + case host: + match = !strcasecmp(newsServer->GetHost(), ref->GetHost()); break; - case ePort: - bMatch = pNewsServer->GetPort() == pRef->GetPort(); + case port: + match = newsServer->GetPort() == ref->GetPort(); break; - case eUser: - bMatch = !strcasecmp(pNewsServer->GetUser(), pRef->GetUser()); + case user: + match = !strcasecmp(newsServer->GetUser(), ref->GetUser()); break; } - if (bMatch && !pRef->GetMatched()) + if (match && !ref->GetMatched()) { it++; index++; } else { - pRefs->erase(it); - it = pRefs->begin() + index; + refs->erase(it); + it = refs->begin() + index; } } - if (pRefs->size() == 0 && bKeepIfNothing) + if (refs->size() == 0 && keepIfNothing) { - pRefs->insert(pRefs->begin(), originalRefs.begin(), originalRefs.end()); + refs->insert(refs->begin(), originalRefs.begin(), originalRefs.end()); } } -void MatchServers(Servers* pServers, ServerRefList* pServerRefs) +void MatchServers(Servers* servers, ServerRefList* serverRefs) { // Step 1: trying perfect match - for (Servers::iterator it = pServers->begin(); it != pServers->end(); it++) + for (Servers::iterator it = servers->begin(); it != servers->end(); it++) { - NewsServer* pNewsServer = *it; + NewsServer* newsServer = *it; ServerRefList matchedRefs; - matchedRefs.insert(matchedRefs.begin(), pServerRefs->begin(), pServerRefs->end()); - FindCandidates(pNewsServer, &matchedRefs, eName, false); - FindCandidates(pNewsServer, &matchedRefs, eHost, false); - FindCandidates(pNewsServer, &matchedRefs, ePort, false); - FindCandidates(pNewsServer, &matchedRefs, eUser, false); + matchedRefs.insert(matchedRefs.begin(), serverRefs->begin(), serverRefs->end()); + FindCandidates(newsServer, &matchedRefs, name, false); + FindCandidates(newsServer, &matchedRefs, host, false); + FindCandidates(newsServer, &matchedRefs, port, false); + FindCandidates(newsServer, &matchedRefs, user, false); if (matchedRefs.size() == 1) { - ServerRef* pRef = matchedRefs.front(); - pNewsServer->SetStateID(pRef->GetStateID()); - pRef->SetMatched(true); - pRef->SetPerfect(true); + ServerRef* ref = matchedRefs.front(); + newsServer->SetStateID(ref->GetStateID()); + ref->SetMatched(true); + ref->SetPerfect(true); } } // Step 2: matching host, port, username and server-name - for (Servers::iterator it = pServers->begin(); it != pServers->end(); it++) + for (Servers::iterator it = servers->begin(); it != servers->end(); it++) { - NewsServer* pNewsServer = *it; - if (!pNewsServer->GetStateID()) + NewsServer* newsServer = *it; + if (!newsServer->GetStateID()) { ServerRefList matchedRefs; - matchedRefs.insert(matchedRefs.begin(), pServerRefs->begin(), pServerRefs->end()); + matchedRefs.insert(matchedRefs.begin(), serverRefs->begin(), serverRefs->end()); - FindCandidates(pNewsServer, &matchedRefs, eHost, false); + FindCandidates(newsServer, &matchedRefs, host, false); if (matchedRefs.size() > 1) { - FindCandidates(pNewsServer, &matchedRefs, eName, true); + FindCandidates(newsServer, &matchedRefs, name, true); } if (matchedRefs.size() > 1) { - FindCandidates(pNewsServer, &matchedRefs, eUser, true); + FindCandidates(newsServer, &matchedRefs, user, true); } if (matchedRefs.size() > 1) { - FindCandidates(pNewsServer, &matchedRefs, ePort, true); + FindCandidates(newsServer, &matchedRefs, port, true); } if (!matchedRefs.empty()) { - ServerRef* pRef = matchedRefs.front(); - pNewsServer->SetStateID(pRef->GetStateID()); - pRef->SetMatched(true); + ServerRef* ref = matchedRefs.front(); + newsServer->SetStateID(ref->GetStateID()); + ref->SetMatched(true); } } } @@ -2741,63 +2741,63 @@ void MatchServers(Servers* pServers, ServerRefList* pServerRefs) *************************************************************************************** */ -bool DiskState::LoadServerInfo(Servers* pServers, FILE* infile, int iFormatVersion, bool* pPerfectMatch) +bool DiskState::LoadServerInfo(Servers* servers, FILE* infile, int formatVersion, bool* perfectMatch) { debug("Loading server info from disk"); ServerRefList serverRefs; - *pPerfectMatch = true; + *perfectMatch = true; int size; if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - char szName[1024]; - if (!fgets(szName, sizeof(szName), infile)) goto error; - if (szName[0] != 0) szName[strlen(szName)-1] = 0; // remove traling '\n' + char name[1024]; + if (!fgets(name, sizeof(name), infile)) goto error; + if (name[0] != 0) name[strlen(name)-1] = 0; // remove traling '\n' - char szHost[200]; - if (!fgets(szHost, sizeof(szHost), infile)) goto error; - if (szHost[0] != 0) szHost[strlen(szHost)-1] = 0; // remove traling '\n' + char host[200]; + if (!fgets(host, sizeof(host), infile)) goto error; + if (host[0] != 0) host[strlen(host)-1] = 0; // remove traling '\n' - int iPort; - if (fscanf(infile, "%i\n", &iPort) != 1) goto error; + int port; + if (fscanf(infile, "%i\n", &port) != 1) goto error; - char szUser[100]; - if (!fgets(szUser, sizeof(szUser), infile)) goto error; - if (szUser[0] != 0) szUser[strlen(szUser)-1] = 0; // remove traling '\n' + char user[100]; + if (!fgets(user, sizeof(user), infile)) goto error; + if (user[0] != 0) user[strlen(user)-1] = 0; // remove traling '\n' - ServerRef* pRef = new ServerRef(); - pRef->m_iStateID = i + 1; - pRef->m_szName = strdup(szName); - pRef->m_szHost = strdup(szHost); - pRef->m_iPort = iPort; - pRef->m_szUser = strdup(szUser); - pRef->m_bMatched = false; - pRef->m_bPerfect = false; - serverRefs.push_back(pRef); + ServerRef* ref = new ServerRef(); + ref->m_stateId = i + 1; + ref->m_name = strdup(name); + ref->m_host = strdup(host); + ref->m_port = port; + ref->m_user = strdup(user); + ref->m_matched = false; + ref->m_perfect = false; + serverRefs.push_back(ref); } - MatchServers(pServers, &serverRefs); + MatchServers(servers, &serverRefs); for (ServerRefList::iterator it = serverRefs.begin(); it != serverRefs.end(); it++) { - ServerRef* pRef = *it; - *pPerfectMatch = *pPerfectMatch && pRef->GetPerfect(); + ServerRef* ref = *it; + *perfectMatch = *perfectMatch && ref->GetPerfect(); delete *it; } debug("******** MATCHING NEWS-SERVERS **********"); - for (Servers::iterator it = pServers->begin(); it != pServers->end(); it++) + for (Servers::iterator it = servers->begin(); it != servers->end(); it++) { - NewsServer* pNewsServer = *it; - *pPerfectMatch = *pPerfectMatch && pNewsServer->GetStateID(); - debug("Server %i -> %i", pNewsServer->GetID(), pNewsServer->GetStateID()); - debug("Server %i.Name: %s", pNewsServer->GetID(), pNewsServer->GetName()); - debug("Server %i.Host: %s:%i", pNewsServer->GetID(), pNewsServer->GetHost(), pNewsServer->GetPort()); + NewsServer* newsServer = *it; + *perfectMatch = *perfectMatch && newsServer->GetStateID(); + debug("Server %i -> %i", newsServer->GetID(), newsServer->GetStateID()); + debug("Server %i.Name: %s", newsServer->GetID(), newsServer->GetName()); + debug("Server %i.Host: %s:%i", newsServer->GetID(), newsServer->GetHost(), newsServer->GetPort()); } - debug("All servers perfectly matched: %s", *pPerfectMatch ? "yes" : "no"); + debug("All servers perfectly matched: %s", *perfectMatch ? "yes" : "no"); return true; @@ -2812,33 +2812,33 @@ error: return false; } -bool DiskState::SaveVolumeStat(ServerVolumes* pServerVolumes, FILE* outfile) +bool DiskState::SaveVolumeStat(ServerVolumes* serverVolumes, FILE* outfile) { debug("Saving volume stats to disk"); - fprintf(outfile, "%i\n", (int)pServerVolumes->size()); - for (ServerVolumes::iterator it = pServerVolumes->begin(); it != pServerVolumes->end(); it++) + fprintf(outfile, "%i\n", (int)serverVolumes->size()); + for (ServerVolumes::iterator it = serverVolumes->begin(); it != serverVolumes->end(); it++) { - ServerVolume* pServerVolume = *it; + ServerVolume* serverVolume = *it; - fprintf(outfile, "%i,%i,%i\n", pServerVolume->GetFirstDay(), (int)pServerVolume->GetDataTime(), (int)pServerVolume->GetCustomTime()); + fprintf(outfile, "%i,%i,%i\n", serverVolume->GetFirstDay(), (int)serverVolume->GetDataTime(), (int)serverVolume->GetCustomTime()); unsigned long High1, Low1, High2, Low2; - Util::SplitInt64(pServerVolume->GetTotalBytes(), &High1, &Low1); - Util::SplitInt64(pServerVolume->GetCustomBytes(), &High2, &Low2); + Util::SplitInt64(serverVolume->GetTotalBytes(), &High1, &Low1); + Util::SplitInt64(serverVolume->GetCustomBytes(), &High2, &Low2); fprintf(outfile, "%lu,%lu,%lu,%lu\n", High1, Low1, High2, Low2); - ServerVolume::VolumeArray* VolumeArrays[] = { pServerVolume->BytesPerSeconds(), - pServerVolume->BytesPerMinutes(), pServerVolume->BytesPerHours(), pServerVolume->BytesPerDays() }; + ServerVolume::VolumeArray* VolumeArrays[] = { serverVolume->BytesPerSeconds(), + serverVolume->BytesPerMinutes(), serverVolume->BytesPerHours(), serverVolume->BytesPerDays() }; for (int i=0; i < 4; i++) { - ServerVolume::VolumeArray* pVolumeArray = VolumeArrays[i]; + ServerVolume::VolumeArray* volumeArray = VolumeArrays[i]; - fprintf(outfile, "%i\n", (int)pVolumeArray->size()); - for (ServerVolume::VolumeArray::iterator it2 = pVolumeArray->begin(); it2 != pVolumeArray->end(); it2++) + fprintf(outfile, "%i\n", (int)volumeArray->size()); + for (ServerVolume::VolumeArray::iterator it2 = volumeArray->begin(); it2 != volumeArray->end(); it2++) { - long long lBytes = *it2; - Util::SplitInt64(lBytes, &High1, &Low1); + long long bytes = *it2; + Util::SplitInt64(bytes, &High1, &Low1); fprintf(outfile, "%lu,%lu\n", High1, Low1); } } @@ -2847,7 +2847,7 @@ bool DiskState::SaveVolumeStat(ServerVolumes* pServerVolumes, FILE* outfile) return true; } -bool DiskState::LoadVolumeStat(Servers* pServers, ServerVolumes* pServerVolumes, FILE* infile, int iFormatVersion) +bool DiskState::LoadVolumeStat(Servers* servers, ServerVolumes* serverVolumes, FILE* infile, int formatVersion) { debug("Loading volume stats from disk"); @@ -2855,58 +2855,58 @@ bool DiskState::LoadVolumeStat(Servers* pServers, ServerVolumes* pServerVolumes, if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) { - ServerVolume* pServerVolume = NULL; + ServerVolume* serverVolume = NULL; if (i == 0) { - pServerVolume = pServerVolumes->at(0); + serverVolume = serverVolumes->at(0); } else { - for (Servers::iterator it = pServers->begin(); it != pServers->end(); it++) + for (Servers::iterator it = servers->begin(); it != servers->end(); it++) { - NewsServer* pNewsServer = *it; - if (pNewsServer->GetStateID() == i) + NewsServer* newsServer = *it; + if (newsServer->GetStateID() == i) { - pServerVolume = pServerVolumes->at(pNewsServer->GetID()); + serverVolume = serverVolumes->at(newsServer->GetID()); } } } - int iFirstDay, iDataTime, iCustomTime; + int firstDay, dataTime, customTime; unsigned long High1, Low1, High2 = 0, Low2 = 0; - if (iFormatVersion >= 3) + if (formatVersion >= 3) { - if (fscanf(infile, "%i,%i,%i\n", &iFirstDay, &iDataTime,&iCustomTime) != 3) goto error; + if (fscanf(infile, "%i,%i,%i\n", &firstDay, &dataTime,&customTime) != 3) goto error; if (fscanf(infile, "%lu,%lu,%lu,%lu\n", &High1, &Low1, &High2, &Low2) != 4) goto error; - if (pServerVolume) pServerVolume->SetCustomTime((time_t)iCustomTime); + if (serverVolume) serverVolume->SetCustomTime((time_t)customTime); } else { - if (fscanf(infile, "%i,%i\n", &iFirstDay, &iDataTime) != 2) goto error; + if (fscanf(infile, "%i,%i\n", &firstDay, &dataTime) != 2) goto error; if (fscanf(infile, "%lu,%lu\n", &High1, &Low1) != 2) goto error; } - if (pServerVolume) pServerVolume->SetFirstDay(iFirstDay); - if (pServerVolume) pServerVolume->SetDataTime((time_t)iDataTime); - if (pServerVolume) pServerVolume->SetTotalBytes(Util::JoinInt64(High1, Low1)); - if (pServerVolume) pServerVolume->SetCustomBytes(Util::JoinInt64(High2, Low2)); + if (serverVolume) serverVolume->SetFirstDay(firstDay); + if (serverVolume) serverVolume->SetDataTime((time_t)dataTime); + if (serverVolume) serverVolume->SetTotalBytes(Util::JoinInt64(High1, Low1)); + if (serverVolume) serverVolume->SetCustomBytes(Util::JoinInt64(High2, Low2)); - ServerVolume::VolumeArray* VolumeArrays[] = { pServerVolume ? pServerVolume->BytesPerSeconds() : NULL, - pServerVolume ? pServerVolume->BytesPerMinutes() : NULL, - pServerVolume ? pServerVolume->BytesPerHours() : NULL, - pServerVolume ? pServerVolume->BytesPerDays() : NULL }; + ServerVolume::VolumeArray* VolumeArrays[] = { serverVolume ? serverVolume->BytesPerSeconds() : NULL, + serverVolume ? serverVolume->BytesPerMinutes() : NULL, + serverVolume ? serverVolume->BytesPerHours() : NULL, + serverVolume ? serverVolume->BytesPerDays() : NULL }; for (int k=0; k < 4; k++) { - ServerVolume::VolumeArray* pVolumeArray = VolumeArrays[k]; + ServerVolume::VolumeArray* volumeArray = VolumeArrays[k]; - int iArrSize; - if (fscanf(infile, "%i\n", &iArrSize) != 1) goto error; - if (pVolumeArray) pVolumeArray->resize(iArrSize); + int arrSize; + if (fscanf(infile, "%i\n", &arrSize) != 1) goto error; + if (volumeArray) volumeArray->resize(arrSize); - for (int j = 0; j < iArrSize; j++) + for (int j = 0; j < arrSize; j++) { if (fscanf(infile, "%lu,%lu\n", &High1, &Low1) != 2) goto error; - if (pVolumeArray) (*pVolumeArray)[j] = Util::JoinInt64(High1, Low1); + if (volumeArray) (*volumeArray)[j] = Util::JoinInt64(High1, Low1); } } } @@ -2921,14 +2921,14 @@ error: void DiskState::WriteCacheFlag() { - char szFlagFilename[1024]; - snprintf(szFlagFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "acache"); - szFlagFilename[1024-1] = '\0'; + char flagFilename[1024]; + snprintf(flagFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "acache"); + flagFilename[1024-1] = '\0'; - FILE* outfile = fopen(szFlagFilename, FOPEN_WB); + FILE* outfile = fopen(flagFilename, FOPEN_WB); if (!outfile) { - error("Error saving diskstate: Could not create file %s", szFlagFilename); + error("Error saving diskstate: Could not create file %s", flagFilename); return; } @@ -2937,30 +2937,30 @@ void DiskState::WriteCacheFlag() void DiskState::DeleteCacheFlag() { - char szFlagFilename[1024]; - snprintf(szFlagFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "acache"); - szFlagFilename[1024-1] = '\0'; + char flagFilename[1024]; + snprintf(flagFilename, 1024, "%s%s", g_pOptions->GetQueueDir(), "acache"); + flagFilename[1024-1] = '\0'; - remove(szFlagFilename); + remove(flagFilename); } -void DiskState::AppendNZBMessage(int iNZBID, Message::EKind eKind, const char* szText) +void DiskState::AppendNZBMessage(int nzbId, Message::EKind kind, const char* text) { - char szLogFilename[1024]; - snprintf(szLogFilename, 1024, "%sn%i.log", g_pOptions->GetQueueDir(), iNZBID); - szLogFilename[1024-1] = '\0'; + char logFilename[1024]; + snprintf(logFilename, 1024, "%sn%i.log", g_pOptions->GetQueueDir(), nzbId); + logFilename[1024-1] = '\0'; - FILE* outfile = fopen(szLogFilename, FOPEN_ABP); + FILE* outfile = fopen(logFilename, FOPEN_ABP); if (!outfile) { - error("Error saving log: Could not create file %s", szLogFilename); + error("Error saving log: Could not create file %s", logFilename); return; } - const char* szMessageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL"}; + const char* messageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL"}; char tmp2[1024]; - strncpy(tmp2, szText, 1024); + strncpy(tmp2, text, 1024); tmp2[1024-1] = '\0'; // replace bad chars @@ -2976,87 +2976,87 @@ void DiskState::AppendNZBMessage(int iNZBID, Message::EKind eKind, const char* s time_t tm = time(NULL); time_t rawtime = tm + g_pOptions->GetTimeCorrection(); - char szTime[50]; + char time[50]; #ifdef HAVE_CTIME_R_3 - ctime_r(&rawtime, szTime, 50); + ctime_r(&rawtime, time, 50); #else - ctime_r(&rawtime, szTime); + ctime_r(&rawtime, time); #endif - szTime[50-1] = '\0'; - szTime[strlen(szTime) - 1] = '\0'; // trim LF + time[50-1] = '\0'; + time[strlen(time) - 1] = '\0'; // trim LF - fprintf(outfile, "%s\t%u\t%s\t%s%s", szTime, (int)tm, szMessageType[eKind], tmp2, LINE_ENDING); + fprintf(outfile, "%s\t%u\t%s\t%s%s", time, (int)tm, messageType[kind], tmp2, LINE_ENDING); fclose(outfile); } -void DiskState::LoadNZBMessages(int iNZBID, MessageList* pMessages) +void DiskState::LoadNZBMessages(int nzbId, MessageList* messages) { // Important: // - Other threads may be writing into the log-file at any time; // - The log-file may also be deleted from another thread; - char szLogFilename[1024]; - snprintf(szLogFilename, 1024, "%sn%i.log", g_pOptions->GetQueueDir(), iNZBID); - szLogFilename[1024-1] = '\0'; + char logFilename[1024]; + snprintf(logFilename, 1024, "%sn%i.log", g_pOptions->GetQueueDir(), nzbId); + logFilename[1024-1] = '\0'; - if (!Util::FileExists(szLogFilename)) + if (!Util::FileExists(logFilename)) { return; } - FILE* infile = fopen(szLogFilename, FOPEN_RB); + FILE* infile = fopen(logFilename, FOPEN_RB); if (!infile) { - error("Error reading log: could not open file %s", szLogFilename); + error("Error reading log: could not open file %s", logFilename); return; } - int iID = 0; - char szLine[1024]; - while (fgets(szLine, sizeof(szLine), infile)) + int id = 0; + char line[1024]; + while (fgets(line, sizeof(line), infile)) { - Util::TrimRight(szLine); + Util::TrimRight(line); // time (skip formatted time first) - char* p = strchr(szLine, '\t'); + char* p = strchr(line, '\t'); if (!p) goto exit; - int iTime = atoi(p + 1); + int time = atoi(p + 1); // kind p = strchr(p + 1, '\t'); if (!p) goto exit; - char* szKind = p + 1; + char* kindStr = p + 1; - Message::EKind eKind = Message::mkError; - if (!strncmp(szKind, "INFO", 4)) + Message::EKind kind = Message::mkError; + if (!strncmp(kindStr, "INFO", 4)) { - eKind = Message::mkInfo; + kind = Message::mkInfo; } - else if (!strncmp(szKind, "WARNING", 7)) + else if (!strncmp(kindStr, "WARNING", 7)) { - eKind = Message::mkWarning; + kind = Message::mkWarning; } - else if (!strncmp(szKind, "ERROR", 5)) + else if (!strncmp(kindStr, "ERROR", 5)) { - eKind = Message::mkError; + kind = Message::mkError; } - else if (!strncmp(szKind, "DETAIL", 6)) + else if (!strncmp(kindStr, "DETAIL", 6)) { - eKind = Message::mkDetail; + kind = Message::mkDetail; } - else if (!strncmp(szKind, "DEBUG", 5)) + else if (!strncmp(kindStr, "DEBUG", 5)) { - eKind = Message::mkDebug; + kind = Message::mkDebug; } // text p = strchr(p + 1, '\t'); if (!p) goto exit; - char* szText = p + 1; + char* text = p + 1; - Message* pMessage = new Message(++iID, eKind, (time_t)iTime, szText); - pMessages->push_back(pMessage); + Message* message = new Message(++id, kind, (time_t)time, text); + messages->push_back(message); } exit: diff --git a/daemon/queue/DiskState.h b/daemon/queue/DiskState.h index c68f5163..c58ca444 100644 --- a/daemon/queue/DiskState.h +++ b/daemon/queue/DiskState.h @@ -36,65 +36,65 @@ class DiskState { private: int fscanf(FILE* infile, const char* Format, ...); - bool SaveFileInfo(FileInfo* pFileInfo, const char* szFilename); - bool LoadFileInfo(FileInfo* pFileInfo, const char* szFilename, bool bFileSummary, bool bArticles); - void SaveNZBQueue(DownloadQueue* pDownloadQueue, FILE* outfile); - bool LoadNZBList(NZBList* pNZBList, Servers* pServers, FILE* infile, int iFormatVersion); - void SaveNZBInfo(NZBInfo* pNZBInfo, FILE* outfile); - bool LoadNZBInfo(NZBInfo* pNZBInfo, Servers* pServers, FILE* infile, int iFormatVersion); - void SavePostQueue(DownloadQueue* pDownloadQueue, FILE* outfile); - void SaveDupInfo(DupInfo* pDupInfo, FILE* outfile); - bool LoadDupInfo(DupInfo* pDupInfo, FILE* infile, int iFormatVersion); - void SaveHistory(DownloadQueue* pDownloadQueue, FILE* outfile); - bool LoadHistory(DownloadQueue* pDownloadQueue, NZBList* pNZBList, Servers* pServers, FILE* infile, int iFormatVersion); - NZBInfo* FindNZBInfo(DownloadQueue* pDownloadQueue, int iID); - bool SaveFeedStatus(Feeds* pFeeds, FILE* outfile); - bool LoadFeedStatus(Feeds* pFeeds, FILE* infile, int iFormatVersion); - bool SaveFeedHistory(FeedHistory* pFeedHistory, FILE* outfile); - bool LoadFeedHistory(FeedHistory* pFeedHistory, FILE* infile, int iFormatVersion); - bool SaveServerInfo(Servers* pServers, FILE* outfile); - bool LoadServerInfo(Servers* pServers, FILE* infile, int iFormatVersion, bool* pPerfectMatch); - bool SaveVolumeStat(ServerVolumes* pServerVolumes, FILE* outfile); - bool LoadVolumeStat(Servers* pServers, ServerVolumes* pServerVolumes, FILE* infile, int iFormatVersion); - void CalcFileStats(DownloadQueue* pDownloadQueue, int iFormatVersion); - void CalcNZBFileStats(NZBInfo* pNZBInfo, int iFormatVersion); - bool LoadAllFileStates(DownloadQueue* pDownloadQueue, Servers* pServers); - void SaveServerStats(ServerStatList* pServerStatList, FILE* outfile); - bool LoadServerStats(ServerStatList* pServerStatList, Servers* pServers, FILE* infile); - bool FinishWriteTransaction(const char* szNewFileName, const char* szDestFileName); + bool SaveFileInfo(FileInfo* fileInfo, const char* filename); + bool LoadFileInfo(FileInfo* fileInfo, const char* filename, bool fileSummary, bool articles); + void SaveNZBQueue(DownloadQueue* downloadQueue, FILE* outfile); + bool LoadNZBList(NZBList* nzbList, Servers* servers, FILE* infile, int formatVersion); + void SaveNZBInfo(NZBInfo* nzbInfo, FILE* outfile); + bool LoadNZBInfo(NZBInfo* nzbInfo, Servers* servers, FILE* infile, int formatVersion); + void SavePostQueue(DownloadQueue* downloadQueue, FILE* outfile); + void SaveDupInfo(DupInfo* dupInfo, FILE* outfile); + bool LoadDupInfo(DupInfo* dupInfo, FILE* infile, int formatVersion); + void SaveHistory(DownloadQueue* downloadQueue, FILE* outfile); + bool LoadHistory(DownloadQueue* downloadQueue, NZBList* nzbList, Servers* servers, FILE* infile, int formatVersion); + NZBInfo* FindNZBInfo(DownloadQueue* downloadQueue, int id); + bool SaveFeedStatus(Feeds* feeds, FILE* outfile); + bool LoadFeedStatus(Feeds* feeds, FILE* infile, int formatVersion); + bool SaveFeedHistory(FeedHistory* feedHistory, FILE* outfile); + bool LoadFeedHistory(FeedHistory* feedHistory, FILE* infile, int formatVersion); + bool SaveServerInfo(Servers* servers, FILE* outfile); + bool LoadServerInfo(Servers* servers, FILE* infile, int formatVersion, bool* perfectMatch); + bool SaveVolumeStat(ServerVolumes* serverVolumes, FILE* outfile); + bool LoadVolumeStat(Servers* servers, ServerVolumes* serverVolumes, FILE* infile, int formatVersion); + void CalcFileStats(DownloadQueue* downloadQueue, int formatVersion); + void CalcNZBFileStats(NZBInfo* nzbInfo, int formatVersion); + bool LoadAllFileStates(DownloadQueue* downloadQueue, Servers* servers); + void SaveServerStats(ServerStatList* serverStatList, FILE* outfile); + bool LoadServerStats(ServerStatList* serverStatList, Servers* servers, FILE* infile); + bool FinishWriteTransaction(const char* newFileName, const char* destFileName); // backward compatibility functions (conversions from older formats) - bool LoadPostQueue12(DownloadQueue* pDownloadQueue, NZBList* pNZBList, FILE* infile, int iFormatVersion); - bool LoadPostQueue5(DownloadQueue* pDownloadQueue, NZBList* pNZBList); - bool LoadUrlQueue12(DownloadQueue* pDownloadQueue, FILE* infile, int iFormatVersion); - bool LoadUrlInfo12(NZBInfo* pNZBInfo, FILE* infile, int iFormatVersion); - int FindNZBInfoIndex(NZBList* pNZBList, NZBInfo* pNZBInfo); + bool LoadPostQueue12(DownloadQueue* downloadQueue, NZBList* nzbList, FILE* infile, int formatVersion); + bool LoadPostQueue5(DownloadQueue* downloadQueue, NZBList* nzbList); + bool LoadUrlQueue12(DownloadQueue* downloadQueue, FILE* infile, int formatVersion); + bool LoadUrlInfo12(NZBInfo* nzbInfo, FILE* infile, int formatVersion); + int FindNZBInfoIndex(NZBList* nzbList, NZBInfo* nzbInfo); void ConvertDupeKey(char* buf, int bufsize); - bool LoadFileQueue12(NZBList* pNZBList, NZBList* pSortList, FILE* infile, int iFormatVersion); - void CompleteNZBList12(DownloadQueue* pDownloadQueue, NZBList* pNZBList, int iFormatVersion); - void CompleteDupList12(DownloadQueue* pDownloadQueue, int iFormatVersion); - void CalcCriticalHealth(NZBList* pNZBList); + bool LoadFileQueue12(NZBList* nzbList, NZBList* sortList, FILE* infile, int formatVersion); + void CompleteNZBList12(DownloadQueue* downloadQueue, NZBList* nzbList, int formatVersion); + void CompleteDupList12(DownloadQueue* downloadQueue, int formatVersion); + void CalcCriticalHealth(NZBList* nzbList); public: bool DownloadQueueExists(); - bool SaveDownloadQueue(DownloadQueue* pDownloadQueue); - bool LoadDownloadQueue(DownloadQueue* pDownloadQueue, Servers* pServers); - bool SaveFile(FileInfo* pFileInfo); - bool SaveFileState(FileInfo* pFileInfo, bool bCompleted); - bool LoadFileState(FileInfo* pFileInfo, Servers* pServers, bool bCompleted); - bool LoadArticles(FileInfo* pFileInfo); + bool SaveDownloadQueue(DownloadQueue* downloadQueue); + bool LoadDownloadQueue(DownloadQueue* downloadQueue, Servers* servers); + bool SaveFile(FileInfo* fileInfo); + bool SaveFileState(FileInfo* fileInfo, bool completed); + bool LoadFileState(FileInfo* fileInfo, Servers* servers, bool completed); + bool LoadArticles(FileInfo* fileInfo); void DiscardDownloadQueue(); - void DiscardFile(FileInfo* pFileInfo, bool bDeleteData, bool bDeletePartialState, bool bDeleteCompletedState); - void DiscardFiles(NZBInfo* pNZBInfo); - bool SaveFeeds(Feeds* pFeeds, FeedHistory* pFeedHistory); - bool LoadFeeds(Feeds* pFeeds, FeedHistory* pFeedHistory); - bool SaveStats(Servers* pServers, ServerVolumes* pServerVolumes); - bool LoadStats(Servers* pServers, ServerVolumes* pServerVolumes, bool* pPerfectMatch); - void CleanupTempDir(DownloadQueue* pDownloadQueue); + void DiscardFile(FileInfo* fileInfo, bool deleteData, bool deletePartialState, bool deleteCompletedState); + void DiscardFiles(NZBInfo* nzbInfo); + bool SaveFeeds(Feeds* feeds, FeedHistory* feedHistory); + bool LoadFeeds(Feeds* feeds, FeedHistory* feedHistory); + bool SaveStats(Servers* servers, ServerVolumes* serverVolumes); + bool LoadStats(Servers* servers, ServerVolumes* serverVolumes, bool* perfectMatch); + void CleanupTempDir(DownloadQueue* downloadQueue); void WriteCacheFlag(); void DeleteCacheFlag(); - void AppendNZBMessage(int iNZBID, Message::EKind eKind, const char* szText); - void LoadNZBMessages(int iNZBID, MessageList* pMessages); + void AppendNZBMessage(int nzbId, Message::EKind kind, const char* text); + void LoadNZBMessages(int nzbId, MessageList* messages); }; extern DiskState* g_pDiskState; diff --git a/daemon/queue/DownloadInfo.cpp b/daemon/queue/DownloadInfo.cpp index 57546995..27bd1bd1 100644 --- a/daemon/queue/DownloadInfo.cpp +++ b/daemon/queue/DownloadInfo.cpp @@ -47,29 +47,29 @@ #include "Options.h" #include "Util.h" -int FileInfo::m_iIDGen = 0; -int FileInfo::m_iIDMax = 0; -int NZBInfo::m_iIDGen = 0; -int NZBInfo::m_iIDMax = 0; +int FileInfo::m_idGen = 0; +int FileInfo::m_idMax = 0; +int NZBInfo::m_idGen = 0; +int NZBInfo::m_idMax = 0; DownloadQueue* DownloadQueue::g_pDownloadQueue = NULL; bool DownloadQueue::g_bLoaded = false; -NZBParameter::NZBParameter(const char* szName) +NZBParameter::NZBParameter(const char* name) { - m_szName = strdup(szName); - m_szValue = NULL; + m_name = strdup(name); + m_value = NULL; } NZBParameter::~NZBParameter() { - free(m_szName); - free(m_szValue); + free(m_name); + free(m_value); } -void NZBParameter::SetValue(const char* szValue) +void NZBParameter::SetValue(const char* value) { - free(m_szValue); - m_szValue = strdup(szValue); + free(m_value); + m_value = strdup(value); } @@ -87,75 +87,75 @@ void NZBParameterList::Clear() clear(); } -void NZBParameterList::SetParameter(const char* szName, const char* szValue) +void NZBParameterList::SetParameter(const char* name, const char* value) { - NZBParameter* pParameter = NULL; - bool bDelete = !szValue || !*szValue; + NZBParameter* parameter = NULL; + bool deleteObj = !value || !*value; for (iterator it = begin(); it != end(); it++) { - NZBParameter* pLookupParameter = *it; - if (!strcmp(pLookupParameter->GetName(), szName)) + NZBParameter* lookupParameter = *it; + if (!strcmp(lookupParameter->GetName(), name)) { - if (bDelete) + if (deleteObj) { - delete pLookupParameter; + delete lookupParameter; erase(it); return; } - pParameter = pLookupParameter; + parameter = lookupParameter; break; } } - if (bDelete) + if (deleteObj) { return; } - if (!pParameter) + if (!parameter) { - pParameter = new NZBParameter(szName); - push_back(pParameter); + parameter = new NZBParameter(name); + push_back(parameter); } - pParameter->SetValue(szValue); + parameter->SetValue(value); } -NZBParameter* NZBParameterList::Find(const char* szName, bool bCaseSensitive) +NZBParameter* NZBParameterList::Find(const char* name, bool caseSensitive) { for (iterator it = begin(); it != end(); it++) { - NZBParameter* pParameter = *it; - if ((bCaseSensitive && !strcmp(pParameter->GetName(), szName)) || - (!bCaseSensitive && !strcasecmp(pParameter->GetName(), szName))) + NZBParameter* parameter = *it; + if ((caseSensitive && !strcmp(parameter->GetName(), name)) || + (!caseSensitive && !strcasecmp(parameter->GetName(), name))) { - return pParameter; + return parameter; } } return NULL; } -void NZBParameterList::CopyFrom(NZBParameterList* pSourceParameters) +void NZBParameterList::CopyFrom(NZBParameterList* sourceParameters) { - for (iterator it = pSourceParameters->begin(); it != pSourceParameters->end(); it++) + for (iterator it = sourceParameters->begin(); it != sourceParameters->end(); it++) { - NZBParameter* pParameter = *it; - SetParameter(pParameter->GetName(), pParameter->GetValue()); + NZBParameter* parameter = *it; + SetParameter(parameter->GetName(), parameter->GetValue()); } } -ScriptStatus::ScriptStatus(const char* szName, EStatus eStatus) +ScriptStatus::ScriptStatus(const char* name, EStatus status) { - m_szName = strdup(szName); - m_eStatus = eStatus; + m_name = strdup(name); + m_status = status; } ScriptStatus::~ScriptStatus() { - free(m_szName); + free(m_name); } @@ -173,35 +173,35 @@ void ScriptStatusList::Clear() clear(); } -void ScriptStatusList::Add(const char* szScriptName, ScriptStatus::EStatus eStatus) +void ScriptStatusList::Add(const char* scriptName, ScriptStatus::EStatus status) { - push_back(new ScriptStatus(szScriptName, eStatus)); + push_back(new ScriptStatus(scriptName, status)); } ScriptStatus::EStatus ScriptStatusList::CalcTotalStatus() { - ScriptStatus::EStatus eStatus = ScriptStatus::srNone; + ScriptStatus::EStatus status = ScriptStatus::srNone; for (iterator it = begin(); it != end(); it++) { - ScriptStatus* pScriptStatus = *it; + ScriptStatus* scriptStatus = *it; // Failure-Status overrides Success-Status - if ((pScriptStatus->GetStatus() == ScriptStatus::srSuccess && eStatus == ScriptStatus::srNone) || - (pScriptStatus->GetStatus() == ScriptStatus::srFailure)) + if ((scriptStatus->GetStatus() == ScriptStatus::srSuccess && status == ScriptStatus::srNone) || + (scriptStatus->GetStatus() == ScriptStatus::srFailure)) { - eStatus = pScriptStatus->GetStatus(); + status = scriptStatus->GetStatus(); } } - return eStatus; + return status; } -ServerStat::ServerStat(int iServerID) +ServerStat::ServerStat(int serverId) { - m_iServerID = iServerID; - m_iSuccessArticles = 0; - m_iFailedArticles = 0; + m_serverId = serverId; + m_successArticles = 0; + m_failedArticles = 0; } @@ -219,177 +219,177 @@ void ServerStatList::Clear() clear(); } -void ServerStatList::StatOp(int iServerID, int iSuccessArticles, int iFailedArticles, EStatOperation eStatOperation) +void ServerStatList::StatOp(int serverId, int successArticles, int failedArticles, EStatOperation statOperation) { - ServerStat* pServerStat = NULL; + ServerStat* serverStat = NULL; for (iterator it = begin(); it != end(); it++) { - ServerStat* pServerStat1 = *it; - if (pServerStat1->GetServerID() == iServerID) + ServerStat* serverStat1 = *it; + if (serverStat1->GetServerID() == serverId) { - pServerStat = pServerStat1; + serverStat = serverStat1; break; } } - if (!pServerStat) + if (!serverStat) { - pServerStat = new ServerStat(iServerID); - push_back(pServerStat); + serverStat = new ServerStat(serverId); + push_back(serverStat); } - switch (eStatOperation) + switch (statOperation) { case soSet: - pServerStat->SetSuccessArticles(iSuccessArticles); - pServerStat->SetFailedArticles(iFailedArticles); + serverStat->SetSuccessArticles(successArticles); + serverStat->SetFailedArticles(failedArticles); break; case soAdd: - pServerStat->SetSuccessArticles(pServerStat->GetSuccessArticles() + iSuccessArticles); - pServerStat->SetFailedArticles(pServerStat->GetFailedArticles() + iFailedArticles); + serverStat->SetSuccessArticles(serverStat->GetSuccessArticles() + successArticles); + serverStat->SetFailedArticles(serverStat->GetFailedArticles() + failedArticles); break; case soSubtract: - pServerStat->SetSuccessArticles(pServerStat->GetSuccessArticles() - iSuccessArticles); - pServerStat->SetFailedArticles(pServerStat->GetFailedArticles() - iFailedArticles); + serverStat->SetSuccessArticles(serverStat->GetSuccessArticles() - successArticles); + serverStat->SetFailedArticles(serverStat->GetFailedArticles() - failedArticles); break; } } -void ServerStatList::ListOp(ServerStatList* pServerStats, EStatOperation eStatOperation) +void ServerStatList::ListOp(ServerStatList* serverStats, EStatOperation statOperation) { - for (iterator it = pServerStats->begin(); it != pServerStats->end(); it++) + for (iterator it = serverStats->begin(); it != serverStats->end(); it++) { - ServerStat* pServerStat = *it; - StatOp(pServerStat->GetServerID(), pServerStat->GetSuccessArticles(), pServerStat->GetFailedArticles(), eStatOperation); + ServerStat* serverStat = *it; + StatOp(serverStat->GetServerID(), serverStat->GetSuccessArticles(), serverStat->GetFailedArticles(), statOperation); } } -NZBInfo::NZBInfo() : m_FileList(true) +NZBInfo::NZBInfo() : m_fileList(true) { debug("Creating NZBInfo"); - m_eKind = nkNzb; - m_szURL = strdup(""); - m_szFilename = strdup(""); - m_szDestDir = strdup(""); - m_szFinalDir = strdup(""); - m_szCategory = strdup(""); - m_szName = NULL; - m_iFileCount = 0; - m_iParkedFileCount = 0; - m_lSize = 0; - m_lSuccessSize = 0; - m_lFailedSize = 0; - m_lCurrentSuccessSize = 0; - m_lCurrentFailedSize = 0; - m_lParSize = 0; - m_lParSuccessSize = 0; - m_lParFailedSize = 0; - m_lParCurrentSuccessSize = 0; - m_lParCurrentFailedSize = 0; - m_iTotalArticles = 0; - m_iSuccessArticles = 0; - m_iFailedArticles = 0; - m_iCurrentSuccessArticles = 0; - m_iCurrentFailedArticles = 0; - m_eRenameStatus = rsNone; - m_eParStatus = psNone; - m_eUnpackStatus = usNone; - m_eCleanupStatus = csNone; - m_eMoveStatus = msNone; - m_eDeleteStatus = dsNone; - m_eMarkStatus = ksNone; - m_eUrlStatus = lsNone; - m_iExtraParBlocks = 0; - m_bAddUrlPaused = false; - m_bDeleting = false; - m_bDeletePaused = false; - m_bManyDupeFiles = false; - m_bAvoidHistory = false; - m_bHealthPaused = false; - m_bParCleanup = false; - m_bCleanupDisk = false; - m_bUnpackCleanedUpDisk = false; - m_szQueuedFilename = strdup(""); - m_szDupeKey = strdup(""); - m_iDupeScore = 0; - m_eDupeMode = dmScore; - m_iFullContentHash = 0; - m_iFilteredContentHash = 0; - m_iPausedFileCount = 0; - m_lRemainingSize = 0; - m_lPausedSize = 0; - m_iRemainingParCount = 0; - m_tMinTime = 0; - m_tMaxTime = 0; - m_iPriority = 0; - m_iActiveDownloads = 0; - m_Messages.clear(); - m_pPostInfo = NULL; - m_iIDMessageGen = 0; - m_iID = ++m_iIDGen; - m_lDownloadedSize = 0; - m_iDownloadSec = 0; - m_iPostTotalSec = 0; - m_iParSec = 0; - m_iRepairSec = 0; - m_iUnpackSec = 0; - m_tDownloadStartTime = 0; - m_bReprocess = false; - m_tQueueScriptTime = 0; - m_bParFull = false; - m_iMessageCount = 0; - m_iCachedMessageCount = 0; - m_iFeedID = 0; + m_kind = nkNzb; + m_url = strdup(""); + m_filename = strdup(""); + m_destDir = strdup(""); + m_finalDir = strdup(""); + m_category = strdup(""); + m_name = NULL; + m_fileCount = 0; + m_parkedFileCount = 0; + m_size = 0; + m_successSize = 0; + m_failedSize = 0; + m_currentSuccessSize = 0; + m_currentFailedSize = 0; + m_parSize = 0; + m_parSuccessSize = 0; + m_parFailedSize = 0; + m_parCurrentSuccessSize = 0; + m_parCurrentFailedSize = 0; + m_totalArticles = 0; + m_successArticles = 0; + m_failedArticles = 0; + m_currentSuccessArticles = 0; + m_currentFailedArticles = 0; + m_renameStatus = rsNone; + m_parStatus = psNone; + m_unpackStatus = usNone; + m_cleanupStatus = csNone; + m_moveStatus = msNone; + m_deleteStatus = dsNone; + m_markStatus = ksNone; + m_urlStatus = lsNone; + m_extraParBlocks = 0; + m_addUrlPaused = false; + m_deleting = false; + m_deletePaused = false; + m_manyDupeFiles = false; + m_avoidHistory = false; + m_healthPaused = false; + m_parCleanup = false; + m_cleanupDisk = false; + m_unpackCleanedUpDisk = false; + m_queuedFilename = strdup(""); + m_dupeKey = strdup(""); + m_dupeScore = 0; + m_dupeMode = dmScore; + m_fullContentHash = 0; + m_filteredContentHash = 0; + m_pausedFileCount = 0; + m_remainingSize = 0; + m_pausedSize = 0; + m_remainingParCount = 0; + m_minTime = 0; + m_maxTime = 0; + m_priority = 0; + m_activeDownloads = 0; + m_messages.clear(); + m_postInfo = NULL; + m_idMessageGen = 0; + m_id = ++m_idGen; + m_downloadedSize = 0; + m_downloadSec = 0; + m_postTotalSec = 0; + m_parSec = 0; + m_repairSec = 0; + m_unpackSec = 0; + m_downloadStartTime = 0; + m_reprocess = false; + m_queueScriptTime = 0; + m_parFull = false; + m_messageCount = 0; + m_cachedMessageCount = 0; + m_feedId = 0; } NZBInfo::~NZBInfo() { debug("Destroying NZBInfo"); - free(m_szURL); - free(m_szFilename); - free(m_szDestDir); - free(m_szFinalDir); - free(m_szCategory); - free(m_szName); - free(m_szQueuedFilename); - free(m_szDupeKey); - delete m_pPostInfo; + free(m_url); + free(m_filename); + free(m_destDir); + free(m_finalDir); + free(m_category); + free(m_name); + free(m_queuedFilename); + free(m_dupeKey); + delete m_postInfo; ClearCompletedFiles(); - m_FileList.Clear(); + m_fileList.Clear(); } -void NZBInfo::SetID(int iID) +void NZBInfo::SetID(int id) { - m_iID = iID; - if (m_iIDMax < m_iID) + m_id = id; + if (m_idMax < m_id) { - m_iIDMax = m_iID; + m_idMax = m_id; } } -void NZBInfo::ResetGenID(bool bMax) +void NZBInfo::ResetGenID(bool max) { - if (bMax) + if (max) { - m_iIDGen = m_iIDMax; + m_idGen = m_idMax; } else { - m_iIDGen = 0; - m_iIDMax = 0; + m_idGen = 0; + m_idMax = 0; } } int NZBInfo::GenerateID() { - return ++m_iIDGen; + return ++m_idGen; } void NZBInfo::ClearCompletedFiles() @@ -401,87 +401,87 @@ void NZBInfo::ClearCompletedFiles() m_completedFiles.clear(); } -void NZBInfo::SetDestDir(const char* szDestDir) +void NZBInfo::SetDestDir(const char* destDir) { - free(m_szDestDir); - m_szDestDir = strdup(szDestDir); + free(m_destDir); + m_destDir = strdup(destDir); } -void NZBInfo::SetFinalDir(const char* szFinalDir) +void NZBInfo::SetFinalDir(const char* finalDir) { - free(m_szFinalDir); - m_szFinalDir = strdup(szFinalDir); + free(m_finalDir); + m_finalDir = strdup(finalDir); } -void NZBInfo::SetURL(const char* szURL) +void NZBInfo::SetURL(const char* url) { - free(m_szURL); - m_szURL = strdup(szURL); + free(m_url); + m_url = strdup(url); - if (!m_szName) + if (!m_name) { - char szNZBNicename[1024]; - MakeNiceUrlName(szURL, m_szFilename, szNZBNicename, sizeof(szNZBNicename)); - szNZBNicename[1024-1] = '\0'; + char nzbNicename[1024]; + MakeNiceUrlName(url, m_filename, nzbNicename, sizeof(nzbNicename)); + nzbNicename[1024-1] = '\0'; #ifdef WIN32 - WebUtil::AnsiToUtf8(szNZBNicename, 1024); + WebUtil::AnsiToUtf8(nzbNicename, 1024); #endif - SetName(szNZBNicename); + SetName(nzbNicename); } } -void NZBInfo::SetFilename(const char* szFilename) +void NZBInfo::SetFilename(const char* filename) { - bool bHadFilename = !Util::EmptyStr(m_szFilename); + bool hadFilename = !Util::EmptyStr(m_filename); - free(m_szFilename); - m_szFilename = strdup(szFilename); + free(m_filename); + m_filename = strdup(filename); - if ((!m_szName || !bHadFilename) && !Util::EmptyStr(szFilename)) + if ((!m_name || !hadFilename) && !Util::EmptyStr(filename)) { - char szNZBNicename[1024]; - MakeNiceNZBName(m_szFilename, szNZBNicename, sizeof(szNZBNicename), true); - szNZBNicename[1024-1] = '\0'; + char nzbNicename[1024]; + MakeNiceNZBName(m_filename, nzbNicename, sizeof(nzbNicename), true); + nzbNicename[1024-1] = '\0'; #ifdef WIN32 - WebUtil::AnsiToUtf8(szNZBNicename, 1024); + WebUtil::AnsiToUtf8(nzbNicename, 1024); #endif - SetName(szNZBNicename); + SetName(nzbNicename); } } -void NZBInfo::SetName(const char* szName) +void NZBInfo::SetName(const char* name) { - free(m_szName); - m_szName = szName ? strdup(szName) : NULL; + free(m_name); + m_name = name ? strdup(name) : NULL; } -void NZBInfo::SetCategory(const char* szCategory) +void NZBInfo::SetCategory(const char* category) { - free(m_szCategory); - m_szCategory = strdup(szCategory); + free(m_category); + m_category = strdup(category); } -void NZBInfo::SetQueuedFilename(const char * szQueuedFilename) +void NZBInfo::SetQueuedFilename(const char * queuedFilename) { - free(m_szQueuedFilename); - m_szQueuedFilename = strdup(szQueuedFilename); + free(m_queuedFilename); + m_queuedFilename = strdup(queuedFilename); } -void NZBInfo::SetDupeKey(const char* szDupeKey) +void NZBInfo::SetDupeKey(const char* dupeKey) { - free(m_szDupeKey); - m_szDupeKey = strdup(szDupeKey ? szDupeKey : ""); + free(m_dupeKey); + m_dupeKey = strdup(dupeKey ? dupeKey : ""); } -void NZBInfo::MakeNiceNZBName(const char * szNZBFilename, char * szBuffer, int iSize, bool bRemoveExt) +void NZBInfo::MakeNiceNZBName(const char * nzbFilename, char * buffer, int size, bool removeExt) { char postname[1024]; - const char* szBaseName = Util::BaseFileName(szNZBFilename); + const char* baseName = Util::BaseFileName(nzbFilename); - strncpy(postname, szBaseName, 1024); + strncpy(postname, baseName, 1024); postname[1024-1] = '\0'; - if (bRemoveExt) + if (removeExt) { // wipe out ".nzb" char* p = strrchr(postname, '.'); @@ -490,168 +490,168 @@ void NZBInfo::MakeNiceNZBName(const char * szNZBFilename, char * szBuffer, int i Util::MakeValidFilename(postname, '_', false); - strncpy(szBuffer, postname, iSize); - szBuffer[iSize-1] = '\0'; + strncpy(buffer, postname, size); + buffer[size-1] = '\0'; } -void NZBInfo::MakeNiceUrlName(const char* szURL, const char* szNZBFilename, char* szBuffer, int iSize) +void NZBInfo::MakeNiceUrlName(const char* urlStr, const char* nzbFilename, char* buffer, int size) { - URL url(szURL); + URL url(urlStr); - if (!Util::EmptyStr(szNZBFilename)) + if (!Util::EmptyStr(nzbFilename)) { - char szNZBNicename[1024]; - MakeNiceNZBName(szNZBFilename, szNZBNicename, sizeof(szNZBNicename), true); - snprintf(szBuffer, iSize, "%s @ %s", szNZBNicename, url.GetHost()); + char nzbNicename[1024]; + MakeNiceNZBName(nzbFilename, nzbNicename, sizeof(nzbNicename), true); + snprintf(buffer, size, "%s @ %s", nzbNicename, url.GetHost()); } else if (url.IsValid()) { - snprintf(szBuffer, iSize, "%s%s", url.GetHost(), url.GetResource()); + snprintf(buffer, size, "%s%s", url.GetHost(), url.GetResource()); } else { - snprintf(szBuffer, iSize, "%s", szURL); + snprintf(buffer, size, "%s", urlStr); } - szBuffer[iSize-1] = '\0'; + buffer[size-1] = '\0'; } void NZBInfo::BuildDestDirName() { - char szDestDir[1024]; + char destDir[1024]; if (Util::EmptyStr(g_pOptions->GetInterDir())) { - BuildFinalDirName(szDestDir, 1024); + BuildFinalDirName(destDir, 1024); } else { - snprintf(szDestDir, 1024, "%s%s.#%i", g_pOptions->GetInterDir(), GetName(), GetID()); - szDestDir[1024-1] = '\0'; + snprintf(destDir, 1024, "%s%s.#%i", g_pOptions->GetInterDir(), GetName(), GetID()); + destDir[1024-1] = '\0'; } #ifdef WIN32 - WebUtil::Utf8ToAnsi(szDestDir, 1024); + WebUtil::Utf8ToAnsi(destDir, 1024); #endif - SetDestDir(szDestDir); + SetDestDir(destDir); } -void NZBInfo::BuildFinalDirName(char* szFinalDirBuf, int iBufSize) +void NZBInfo::BuildFinalDirName(char* finalDirBuf, int bufSize) { - char szBuffer[1024]; - bool bUseCategory = m_szCategory && m_szCategory[0] != '\0'; + char buffer[1024]; + bool useCategory = m_category && m_category[0] != '\0'; - snprintf(szFinalDirBuf, iBufSize, "%s", g_pOptions->GetDestDir()); - szFinalDirBuf[iBufSize-1] = '\0'; + snprintf(finalDirBuf, bufSize, "%s", g_pOptions->GetDestDir()); + finalDirBuf[bufSize-1] = '\0'; - if (bUseCategory) + if (useCategory) { - Options::Category *pCategory = g_pOptions->FindCategory(m_szCategory, false); - if (pCategory && pCategory->GetDestDir() && pCategory->GetDestDir()[0] != '\0') + Options::Category *category = g_pOptions->FindCategory(m_category, false); + if (category && category->GetDestDir() && category->GetDestDir()[0] != '\0') { - snprintf(szFinalDirBuf, iBufSize, "%s", pCategory->GetDestDir()); - szFinalDirBuf[iBufSize-1] = '\0'; - bUseCategory = false; + snprintf(finalDirBuf, bufSize, "%s", category->GetDestDir()); + finalDirBuf[bufSize-1] = '\0'; + useCategory = false; } } - if (g_pOptions->GetAppendCategoryDir() && bUseCategory) + if (g_pOptions->GetAppendCategoryDir() && useCategory) { - char szCategoryDir[1024]; - strncpy(szCategoryDir, m_szCategory, 1024); - szCategoryDir[1024 - 1] = '\0'; - Util::MakeValidFilename(szCategoryDir, '_', true); + char categoryDir[1024]; + strncpy(categoryDir, m_category, 1024); + categoryDir[1024 - 1] = '\0'; + Util::MakeValidFilename(categoryDir, '_', true); - snprintf(szBuffer, 1024, "%s%s%c", szFinalDirBuf, szCategoryDir, PATH_SEPARATOR); - szBuffer[1024-1] = '\0'; - strncpy(szFinalDirBuf, szBuffer, iBufSize); + snprintf(buffer, 1024, "%s%s%c", finalDirBuf, categoryDir, PATH_SEPARATOR); + buffer[1024-1] = '\0'; + strncpy(finalDirBuf, buffer, bufSize); } - snprintf(szBuffer, 1024, "%s%s", szFinalDirBuf, GetName()); - szBuffer[1024-1] = '\0'; - strncpy(szFinalDirBuf, szBuffer, iBufSize); + snprintf(buffer, 1024, "%s%s", finalDirBuf, GetName()); + buffer[1024-1] = '\0'; + strncpy(finalDirBuf, buffer, bufSize); #ifdef WIN32 - WebUtil::Utf8ToAnsi(szFinalDirBuf, iBufSize); + WebUtil::Utf8ToAnsi(finalDirBuf, bufSize); #endif } int NZBInfo::CalcHealth() { - if (m_lCurrentFailedSize == 0 || m_lSize == m_lParSize) + if (m_currentFailedSize == 0 || m_size == m_parSize) { return 1000; } - int iHealth = (int)((m_lSize - m_lParSize - - (m_lCurrentFailedSize - m_lParCurrentFailedSize)) * 1000 / (m_lSize - m_lParSize)); + int health = (int)((m_size - m_parSize - + (m_currentFailedSize - m_parCurrentFailedSize)) * 1000 / (m_size - m_parSize)); - if (iHealth == 1000 && m_lCurrentFailedSize - m_lParCurrentFailedSize > 0) + if (health == 1000 && m_currentFailedSize - m_parCurrentFailedSize > 0) { - iHealth = 999; + health = 999; } - return iHealth; + return health; } -int NZBInfo::CalcCriticalHealth(bool bAllowEstimation) +int NZBInfo::CalcCriticalHealth(bool allowEstimation) { - if (m_lSize == 0) + if (m_size == 0) { return 1000; } - if (m_lSize == m_lParSize) + if (m_size == m_parSize) { return 0; } - long long lGoodParSize = m_lParSize - m_lParCurrentFailedSize; - int iCriticalHealth = (int)((m_lSize - lGoodParSize*2) * 1000 / (m_lSize - lGoodParSize)); + long long goodParSize = m_parSize - m_parCurrentFailedSize; + int criticalHealth = (int)((m_size - goodParSize*2) * 1000 / (m_size - goodParSize)); - if (lGoodParSize*2 > m_lSize) + if (goodParSize*2 > m_size) { - iCriticalHealth = 0; + criticalHealth = 0; } - else if (iCriticalHealth == 1000 && m_lParSize > 0) + else if (criticalHealth == 1000 && m_parSize > 0) { - iCriticalHealth = 999; + criticalHealth = 999; } - if (iCriticalHealth == 1000 && bAllowEstimation) + if (criticalHealth == 1000 && allowEstimation) { // using empirical critical health 85%, to avoid false alarms for downloads with renamed par-files - iCriticalHealth = 850; + criticalHealth = 850; } - return iCriticalHealth; + return criticalHealth; } void NZBInfo::UpdateMinMaxTime() { - m_tMinTime = 0; - m_tMaxTime = 0; + m_minTime = 0; + m_maxTime = 0; - bool bFirst = true; - for (FileList::iterator it = m_FileList.begin(); it != m_FileList.end(); it++) + bool first = true; + for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); it++) { - FileInfo* pFileInfo = *it; - if (bFirst) + FileInfo* fileInfo = *it; + if (first) { - m_tMinTime = pFileInfo->GetTime(); - m_tMaxTime = pFileInfo->GetTime(); - bFirst = false; + m_minTime = fileInfo->GetTime(); + m_maxTime = fileInfo->GetTime(); + first = false; } - if (pFileInfo->GetTime() > 0) + if (fileInfo->GetTime() > 0) { - if (pFileInfo->GetTime() < m_tMinTime) + if (fileInfo->GetTime() < m_minTime) { - m_tMinTime = pFileInfo->GetTime(); + m_minTime = fileInfo->GetTime(); } - if (pFileInfo->GetTime() > m_tMaxTime) + if (fileInfo->GetTime() > m_maxTime) { - m_tMaxTime = pFileInfo->GetTime(); + m_maxTime = fileInfo->GetTime(); } } } @@ -659,315 +659,315 @@ void NZBInfo::UpdateMinMaxTime() MessageList* NZBInfo::LockCachedMessages() { - m_mutexLog.Lock(); - return &m_Messages; + m_logMutex.Lock(); + return &m_messages; } void NZBInfo::UnlockCachedMessages() { - m_mutexLog.Unlock(); + m_logMutex.Unlock(); } -void NZBInfo::AddMessage(Message::EKind eKind, const char * szText) +void NZBInfo::AddMessage(Message::EKind kind, const char * text) { - switch (eKind) + switch (kind) { case Message::mkDetail: - detail("%s", szText); + detail("%s", text); break; case Message::mkInfo: - info("%s", szText); + info("%s", text); break; case Message::mkWarning: - warn("%s", szText); + warn("%s", text); break; case Message::mkError: - error("%s", szText); + error("%s", text); break; case Message::mkDebug: - debug("%s", szText); + debug("%s", text); break; } - m_mutexLog.Lock(); - Message* pMessage = new Message(++m_iIDMessageGen, eKind, time(NULL), szText); - m_Messages.push_back(pMessage); + m_logMutex.Lock(); + Message* message = new Message(++m_idMessageGen, kind, time(NULL), text); + m_messages.push_back(message); if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode() && g_pOptions->GetNzbLog()) { - g_pDiskState->AppendNZBMessage(m_iID, eKind, szText); - m_iMessageCount++; + g_pDiskState->AppendNZBMessage(m_id, kind, text); + m_messageCount++; } - while (m_Messages.size() > (unsigned int)g_pOptions->GetLogBufferSize()) + while (m_messages.size() > (unsigned int)g_pOptions->GetLogBufferSize()) { - Message* pMessage = m_Messages.front(); - delete pMessage; - m_Messages.pop_front(); + Message* message = m_messages.front(); + delete message; + m_messages.pop_front(); } - m_iCachedMessageCount = m_Messages.size(); - m_mutexLog.Unlock(); + m_cachedMessageCount = m_messages.size(); + m_logMutex.Unlock(); } -void NZBInfo::PrintMessage(Message::EKind eKind, const char* szFormat, ...) +void NZBInfo::PrintMessage(Message::EKind kind, const char* format, ...) { char tmp2[1024]; va_list ap; - va_start(ap, szFormat); - vsnprintf(tmp2, 1024, szFormat, ap); + va_start(ap, format); + vsnprintf(tmp2, 1024, format, ap); tmp2[1024-1] = '\0'; va_end(ap); - AddMessage(eKind, tmp2); + AddMessage(kind, tmp2); } void NZBInfo::ClearMessages() { - m_mutexLog.Lock(); - m_Messages.Clear(); - m_iCachedMessageCount = 0; - m_mutexLog.Unlock(); + m_logMutex.Lock(); + m_messages.Clear(); + m_cachedMessageCount = 0; + m_logMutex.Unlock(); } -void NZBInfo::CopyFileList(NZBInfo* pSrcNZBInfo) +void NZBInfo::CopyFileList(NZBInfo* srcNzbInfo) { - m_FileList.Clear(); + m_fileList.Clear(); - for (FileList::iterator it = pSrcNZBInfo->GetFileList()->begin(); it != pSrcNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = srcNzbInfo->GetFileList()->begin(); it != srcNzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - pFileInfo->SetNZBInfo(this); - m_FileList.push_back(pFileInfo); + FileInfo* fileInfo = *it; + fileInfo->SetNZBInfo(this); + m_fileList.push_back(fileInfo); } - pSrcNZBInfo->GetFileList()->clear(); // only remove references + srcNzbInfo->GetFileList()->clear(); // only remove references - SetFullContentHash(pSrcNZBInfo->GetFullContentHash()); - SetFilteredContentHash(pSrcNZBInfo->GetFilteredContentHash()); + SetFullContentHash(srcNzbInfo->GetFullContentHash()); + SetFilteredContentHash(srcNzbInfo->GetFilteredContentHash()); - SetFileCount(pSrcNZBInfo->GetFileCount()); - SetPausedFileCount(pSrcNZBInfo->GetPausedFileCount()); - SetRemainingParCount(pSrcNZBInfo->GetRemainingParCount()); + SetFileCount(srcNzbInfo->GetFileCount()); + SetPausedFileCount(srcNzbInfo->GetPausedFileCount()); + SetRemainingParCount(srcNzbInfo->GetRemainingParCount()); - SetSize(pSrcNZBInfo->GetSize()); - SetRemainingSize(pSrcNZBInfo->GetRemainingSize()); - SetPausedSize(pSrcNZBInfo->GetPausedSize()); - SetSuccessSize(pSrcNZBInfo->GetSuccessSize()); - SetCurrentSuccessSize(pSrcNZBInfo->GetCurrentSuccessSize()); - SetFailedSize(pSrcNZBInfo->GetFailedSize()); - SetCurrentFailedSize(pSrcNZBInfo->GetCurrentFailedSize()); + SetSize(srcNzbInfo->GetSize()); + SetRemainingSize(srcNzbInfo->GetRemainingSize()); + SetPausedSize(srcNzbInfo->GetPausedSize()); + SetSuccessSize(srcNzbInfo->GetSuccessSize()); + SetCurrentSuccessSize(srcNzbInfo->GetCurrentSuccessSize()); + SetFailedSize(srcNzbInfo->GetFailedSize()); + SetCurrentFailedSize(srcNzbInfo->GetCurrentFailedSize()); - SetParSize(pSrcNZBInfo->GetParSize()); - SetParSuccessSize(pSrcNZBInfo->GetParSuccessSize()); - SetParCurrentSuccessSize(pSrcNZBInfo->GetParCurrentSuccessSize()); - SetParFailedSize(pSrcNZBInfo->GetParFailedSize()); - SetParCurrentFailedSize(pSrcNZBInfo->GetParCurrentFailedSize()); + SetParSize(srcNzbInfo->GetParSize()); + SetParSuccessSize(srcNzbInfo->GetParSuccessSize()); + SetParCurrentSuccessSize(srcNzbInfo->GetParCurrentSuccessSize()); + SetParFailedSize(srcNzbInfo->GetParFailedSize()); + SetParCurrentFailedSize(srcNzbInfo->GetParCurrentFailedSize()); - SetTotalArticles(pSrcNZBInfo->GetTotalArticles()); - SetSuccessArticles(pSrcNZBInfo->GetSuccessArticles()); - SetFailedArticles(pSrcNZBInfo->GetFailedArticles()); - SetCurrentSuccessArticles(pSrcNZBInfo->GetSuccessArticles()); - SetCurrentFailedArticles(pSrcNZBInfo->GetFailedArticles()); + SetTotalArticles(srcNzbInfo->GetTotalArticles()); + SetSuccessArticles(srcNzbInfo->GetSuccessArticles()); + SetFailedArticles(srcNzbInfo->GetFailedArticles()); + SetCurrentSuccessArticles(srcNzbInfo->GetSuccessArticles()); + SetCurrentFailedArticles(srcNzbInfo->GetFailedArticles()); - SetMinTime(pSrcNZBInfo->GetMinTime()); - SetMaxTime(pSrcNZBInfo->GetMaxTime()); + SetMinTime(srcNzbInfo->GetMinTime()); + SetMaxTime(srcNzbInfo->GetMaxTime()); } void NZBInfo::EnterPostProcess() { - m_pPostInfo = new PostInfo(); - m_pPostInfo->SetNZBInfo(this); + m_postInfo = new PostInfo(); + m_postInfo->SetNZBInfo(this); } void NZBInfo::LeavePostProcess() { - delete m_pPostInfo; - m_pPostInfo = NULL; + delete m_postInfo; + m_postInfo = NULL; ClearMessages(); } -void NZBInfo::SetActiveDownloads(int iActiveDownloads) +void NZBInfo::SetActiveDownloads(int activeDownloads) { - if (((m_iActiveDownloads == 0 && iActiveDownloads > 0) || - (m_iActiveDownloads > 0 && iActiveDownloads == 0)) && - m_eKind == NZBInfo::nkNzb) + if (((m_activeDownloads == 0 && activeDownloads > 0) || + (m_activeDownloads > 0 && activeDownloads == 0)) && + m_kind == NZBInfo::nkNzb) { - if (iActiveDownloads > 0) + if (activeDownloads > 0) { - m_tDownloadStartTime = time(NULL); + m_downloadStartTime = time(NULL); } else { - m_iDownloadSec += time(NULL) - m_tDownloadStartTime; - m_tDownloadStartTime = 0; + m_downloadSec += time(NULL) - m_downloadStartTime; + m_downloadStartTime = 0; } } - m_iActiveDownloads = iActiveDownloads; + m_activeDownloads = activeDownloads; } bool NZBInfo::IsDupeSuccess() { - bool bFailure = - m_eMarkStatus != NZBInfo::ksSuccess && - m_eMarkStatus != NZBInfo::ksGood && - (m_eDeleteStatus != NZBInfo::dsNone || - m_eMarkStatus == NZBInfo::ksBad || - m_eParStatus == NZBInfo::psFailure || - m_eUnpackStatus == NZBInfo::usFailure || - m_eUnpackStatus == NZBInfo::usPassword || - (m_eParStatus == NZBInfo::psSkipped && - m_eUnpackStatus == NZBInfo::usSkipped && + bool failure = + m_markStatus != NZBInfo::ksSuccess && + m_markStatus != NZBInfo::ksGood && + (m_deleteStatus != NZBInfo::dsNone || + m_markStatus == NZBInfo::ksBad || + m_parStatus == NZBInfo::psFailure || + m_unpackStatus == NZBInfo::usFailure || + m_unpackStatus == NZBInfo::usPassword || + (m_parStatus == NZBInfo::psSkipped && + m_unpackStatus == NZBInfo::usSkipped && CalcHealth() < CalcCriticalHealth(true))); - return !bFailure; + return !failure; } -const char* NZBInfo::MakeTextStatus(bool bIgnoreScriptStatus) +const char* NZBInfo::MakeTextStatus(bool ignoreScriptStatus) { - const char* szStatus = "FAILURE/INTERNAL_ERROR"; + const char* status = "FAILURE/INTERNAL_ERROR"; - if (m_eKind == NZBInfo::nkNzb) + if (m_kind == NZBInfo::nkNzb) { - int iHealth = CalcHealth(); - int iCriticalHealth = CalcCriticalHealth(false); - ScriptStatus::EStatus eScriptStatus = bIgnoreScriptStatus ? ScriptStatus::srSuccess : m_scriptStatuses.CalcTotalStatus(); + int health = CalcHealth(); + int criticalHealth = CalcCriticalHealth(false); + ScriptStatus::EStatus scriptStatus = ignoreScriptStatus ? ScriptStatus::srSuccess : m_scriptStatuses.CalcTotalStatus(); - if (m_eMarkStatus == NZBInfo::ksBad) + if (m_markStatus == NZBInfo::ksBad) { - szStatus = "FAILURE/BAD"; + status = "FAILURE/BAD"; } - else if (m_eMarkStatus == NZBInfo::ksGood) + else if (m_markStatus == NZBInfo::ksGood) { - szStatus = "SUCCESS/GOOD"; + status = "SUCCESS/GOOD"; } - else if (m_eMarkStatus == NZBInfo::ksSuccess) + else if (m_markStatus == NZBInfo::ksSuccess) { - szStatus = "SUCCESS/MARK"; + status = "SUCCESS/MARK"; } - else if (m_eDeleteStatus == NZBInfo::dsHealth) + else if (m_deleteStatus == NZBInfo::dsHealth) { - szStatus = "FAILURE/HEALTH"; + status = "FAILURE/HEALTH"; } - else if (m_eDeleteStatus == NZBInfo::dsManual) + else if (m_deleteStatus == NZBInfo::dsManual) { - szStatus = "DELETED/MANUAL"; + status = "DELETED/MANUAL"; } - else if (m_eDeleteStatus == NZBInfo::dsDupe) + else if (m_deleteStatus == NZBInfo::dsDupe) { - szStatus = "DELETED/DUPE"; + status = "DELETED/DUPE"; } - else if (m_eDeleteStatus == NZBInfo::dsBad) + else if (m_deleteStatus == NZBInfo::dsBad) { - szStatus = "FAILURE/BAD"; + status = "FAILURE/BAD"; } - else if (m_eDeleteStatus == NZBInfo::dsGood) + else if (m_deleteStatus == NZBInfo::dsGood) { - szStatus = "DELETED/GOOD"; + status = "DELETED/GOOD"; } - else if (m_eDeleteStatus == NZBInfo::dsCopy) + else if (m_deleteStatus == NZBInfo::dsCopy) { - szStatus = "DELETED/COPY"; + status = "DELETED/COPY"; } - else if (m_eDeleteStatus == NZBInfo::dsScan) + else if (m_deleteStatus == NZBInfo::dsScan) { - szStatus = "FAILURE/SCAN"; + status = "FAILURE/SCAN"; } - else if (m_eParStatus == NZBInfo::psFailure) + else if (m_parStatus == NZBInfo::psFailure) { - szStatus = "FAILURE/PAR"; + status = "FAILURE/PAR"; } - else if (m_eUnpackStatus == NZBInfo::usFailure) + else if (m_unpackStatus == NZBInfo::usFailure) { - szStatus = "FAILURE/UNPACK"; + status = "FAILURE/UNPACK"; } - else if (m_eMoveStatus == NZBInfo::msFailure) + else if (m_moveStatus == NZBInfo::msFailure) { - szStatus = "FAILURE/MOVE"; + status = "FAILURE/MOVE"; } - else if (m_eParStatus == NZBInfo::psManual) + else if (m_parStatus == NZBInfo::psManual) { - szStatus = "WARNING/DAMAGED"; + status = "WARNING/DAMAGED"; } - else if (m_eParStatus == NZBInfo::psRepairPossible) + else if (m_parStatus == NZBInfo::psRepairPossible) { - szStatus = "WARNING/REPAIRABLE"; + status = "WARNING/REPAIRABLE"; } - else if ((m_eParStatus == NZBInfo::psNone || m_eParStatus == NZBInfo::psSkipped) && - (m_eUnpackStatus == NZBInfo::usNone || m_eUnpackStatus == NZBInfo::usSkipped) && - iHealth < iCriticalHealth) + else if ((m_parStatus == NZBInfo::psNone || m_parStatus == NZBInfo::psSkipped) && + (m_unpackStatus == NZBInfo::usNone || m_unpackStatus == NZBInfo::usSkipped) && + health < criticalHealth) { - szStatus = "FAILURE/HEALTH"; + status = "FAILURE/HEALTH"; } - else if ((m_eParStatus == NZBInfo::psNone || m_eParStatus == NZBInfo::psSkipped) && - (m_eUnpackStatus == NZBInfo::usNone || m_eUnpackStatus == NZBInfo::usSkipped) && - iHealth < 1000 && iHealth >= iCriticalHealth) + else if ((m_parStatus == NZBInfo::psNone || m_parStatus == NZBInfo::psSkipped) && + (m_unpackStatus == NZBInfo::usNone || m_unpackStatus == NZBInfo::usSkipped) && + health < 1000 && health >= criticalHealth) { - szStatus = "WARNING/HEALTH"; + status = "WARNING/HEALTH"; } - else if ((m_eParStatus == NZBInfo::psNone || m_eParStatus == NZBInfo::psSkipped) && - (m_eUnpackStatus == NZBInfo::usNone || m_eUnpackStatus == NZBInfo::usSkipped) && - eScriptStatus != ScriptStatus::srFailure && iHealth == 1000) + else if ((m_parStatus == NZBInfo::psNone || m_parStatus == NZBInfo::psSkipped) && + (m_unpackStatus == NZBInfo::usNone || m_unpackStatus == NZBInfo::usSkipped) && + scriptStatus != ScriptStatus::srFailure && health == 1000) { - szStatus = "SUCCESS/HEALTH"; + status = "SUCCESS/HEALTH"; } - else if (m_eUnpackStatus == NZBInfo::usSpace) + else if (m_unpackStatus == NZBInfo::usSpace) { - szStatus = "WARNING/SPACE"; + status = "WARNING/SPACE"; } - else if (m_eUnpackStatus == NZBInfo::usPassword) + else if (m_unpackStatus == NZBInfo::usPassword) { - szStatus = "WARNING/PASSWORD"; + status = "WARNING/PASSWORD"; } - else if ((m_eUnpackStatus == NZBInfo::usSuccess || - ((m_eUnpackStatus == NZBInfo::usNone || m_eUnpackStatus == NZBInfo::usSkipped) && - m_eParStatus == NZBInfo::psSuccess)) && - eScriptStatus == ScriptStatus::srSuccess) + else if ((m_unpackStatus == NZBInfo::usSuccess || + ((m_unpackStatus == NZBInfo::usNone || m_unpackStatus == NZBInfo::usSkipped) && + m_parStatus == NZBInfo::psSuccess)) && + scriptStatus == ScriptStatus::srSuccess) { - szStatus = "SUCCESS/ALL"; + status = "SUCCESS/ALL"; } - else if (m_eUnpackStatus == NZBInfo::usSuccess && eScriptStatus == ScriptStatus::srNone) + else if (m_unpackStatus == NZBInfo::usSuccess && scriptStatus == ScriptStatus::srNone) { - szStatus = "SUCCESS/UNPACK"; + status = "SUCCESS/UNPACK"; } - else if (m_eParStatus == NZBInfo::psSuccess && eScriptStatus == ScriptStatus::srNone) + else if (m_parStatus == NZBInfo::psSuccess && scriptStatus == ScriptStatus::srNone) { - szStatus = "SUCCESS/PAR"; + status = "SUCCESS/PAR"; } - else if (eScriptStatus == ScriptStatus::srFailure) + else if (scriptStatus == ScriptStatus::srFailure) { - szStatus = "WARNING/SCRIPT"; + status = "WARNING/SCRIPT"; } } - else if (m_eKind == NZBInfo::nkUrl) + else if (m_kind == NZBInfo::nkUrl) { - if (m_eDeleteStatus == NZBInfo::dsManual) + if (m_deleteStatus == NZBInfo::dsManual) { - szStatus = "DELETED/MANUAL"; + status = "DELETED/MANUAL"; } - else if (m_eDeleteStatus == NZBInfo::dsDupe) + else if (m_deleteStatus == NZBInfo::dsDupe) { - szStatus = "DELETED/DUPE"; + status = "DELETED/DUPE"; } else { - const char* szUrlStatusName[] = { "FAILURE/INTERNAL_ERROR", "FAILURE/INTERNAL_ERROR", "FAILURE/INTERNAL_ERROR", + const char* urlStatusName[] = { "FAILURE/INTERNAL_ERROR", "FAILURE/INTERNAL_ERROR", "FAILURE/INTERNAL_ERROR", "FAILURE/FETCH", "FAILURE/INTERNAL_ERROR", "WARNING/SKIPPED", "FAILURE/SCAN" }; - szStatus = szUrlStatusName[m_eUrlStatus]; + status = urlStatusName[m_urlStatus]; } } - return szStatus; + return status; } NZBList::~NZBList() { - if (m_bOwnObjects) + if (m_ownObjects) { Clear(); } @@ -982,35 +982,35 @@ void NZBList::Clear() clear(); } -void NZBList::Add(NZBInfo* pNZBInfo, bool bAddTop) +void NZBList::Add(NZBInfo* nzbInfo, bool addTop) { - if (bAddTop) + if (addTop) { - push_front(pNZBInfo); + push_front(nzbInfo); } else { - push_back(pNZBInfo); + push_back(nzbInfo); } } -void NZBList::Remove(NZBInfo* pNZBInfo) +void NZBList::Remove(NZBInfo* nzbInfo) { - iterator it = std::find(begin(), end(), pNZBInfo); + iterator it = std::find(begin(), end(), nzbInfo); if (it != end()) { erase(it); } } -NZBInfo* NZBList::Find(int iID) +NZBInfo* NZBList::Find(int id) { for (iterator it = begin(); it != end(); it++) { - NZBInfo* pNZBInfo = *it; - if (pNZBInfo->GetID() == iID) + NZBInfo* nzbInfo = *it; + if (nzbInfo->GetID() == id) { - return pNZBInfo; + return nzbInfo; } } @@ -1021,200 +1021,200 @@ NZBInfo* NZBList::Find(int iID) ArticleInfo::ArticleInfo() { //debug("Creating ArticleInfo"); - m_szMessageID = NULL; - m_iSize = 0; - m_pSegmentContent = NULL; - m_iSegmentOffset = 0; - m_iSegmentSize = 0; - m_eStatus = aiUndefined; - m_szResultFilename = NULL; - m_lCrc = 0; + m_messageId = NULL; + m_size = 0; + m_segmentContent = NULL; + m_segmentOffset = 0; + m_segmentSize = 0; + m_status = aiUndefined; + m_resultFilename = NULL; + m_crc = 0; } ArticleInfo::~ ArticleInfo() { //debug("Destroying ArticleInfo"); DiscardSegment(); - free(m_szMessageID); - free(m_szResultFilename); + free(m_messageId); + free(m_resultFilename); } -void ArticleInfo::SetMessageID(const char * szMessageID) +void ArticleInfo::SetMessageID(const char * messageId) { - free(m_szMessageID); - m_szMessageID = strdup(szMessageID); + free(m_messageId); + m_messageId = strdup(messageId); } void ArticleInfo::SetResultFilename(const char * v) { - free(m_szResultFilename); - m_szResultFilename = strdup(v); + free(m_resultFilename); + m_resultFilename = strdup(v); } -void ArticleInfo::AttachSegment(char* pContent, long long iOffset, int iSize) +void ArticleInfo::AttachSegment(char* content, long long offset, int size) { DiscardSegment(); - m_pSegmentContent = pContent; - m_iSegmentOffset = iOffset; - m_iSegmentSize = iSize; + m_segmentContent = content; + m_segmentOffset = offset; + m_segmentSize = size; } void ArticleInfo::DiscardSegment() { - if (m_pSegmentContent) + if (m_segmentContent) { - free(m_pSegmentContent); - m_pSegmentContent = NULL; - g_pArticleCache->Free(m_iSegmentSize); + free(m_segmentContent); + m_segmentContent = NULL; + g_pArticleCache->Free(m_segmentSize); } } -FileInfo::FileInfo(int iID) +FileInfo::FileInfo(int id) { debug("Creating FileInfo"); - m_Articles.clear(); - m_Groups.clear(); - m_szSubject = NULL; - m_szFilename = NULL; - m_szOutputFilename = NULL; - m_pMutexOutputFile = NULL; - m_bFilenameConfirmed = false; - m_lSize = 0; - m_lRemainingSize = 0; - m_lMissedSize = 0; - m_lSuccessSize = 0; - m_lFailedSize = 0; - m_iTotalArticles = 0; - m_iMissedArticles = 0; - m_iFailedArticles = 0; - m_iSuccessArticles = 0; - m_tTime = 0; - m_bPaused = false; - m_bDeleted = false; - m_iCompletedArticles = 0; - m_bParFile = false; - m_bOutputInitialized = false; - m_pNZBInfo = NULL; - m_bExtraPriority = false; - m_iActiveDownloads = 0; - m_bAutoDeleted = false; - m_iCachedArticles = 0; - m_bPartialChanged = false; - m_iID = iID ? iID : ++m_iIDGen; + m_articles.clear(); + m_groups.clear(); + m_subject = NULL; + m_filename = NULL; + m_outputFilename = NULL; + m_mutexOutputFile = NULL; + m_filenameConfirmed = false; + m_size = 0; + m_remainingSize = 0; + m_missedSize = 0; + m_successSize = 0; + m_failedSize = 0; + m_totalArticles = 0; + m_missedArticles = 0; + m_failedArticles = 0; + m_successArticles = 0; + m_time = 0; + m_paused = false; + m_deleted = false; + m_completedArticles = 0; + m_parFile = false; + m_outputInitialized = false; + m_nzbInfo = NULL; + m_extraPriority = false; + m_activeDownloads = 0; + m_autoDeleted = false; + m_cachedArticles = 0; + m_partialChanged = false; + m_id = id ? id : ++m_idGen; } FileInfo::~ FileInfo() { debug("Destroying FileInfo"); - free(m_szSubject); - free(m_szFilename); - free(m_szOutputFilename); - delete m_pMutexOutputFile; + free(m_subject); + free(m_filename); + free(m_outputFilename); + delete m_mutexOutputFile; - for (Groups::iterator it = m_Groups.begin(); it != m_Groups.end() ;it++) + for (Groups::iterator it = m_groups.begin(); it != m_groups.end() ;it++) { free(*it); } - m_Groups.clear(); + m_groups.clear(); ClearArticles(); } void FileInfo::ClearArticles() { - for (Articles::iterator it = m_Articles.begin(); it != m_Articles.end() ;it++) + for (Articles::iterator it = m_articles.begin(); it != m_articles.end() ;it++) { delete *it; } - m_Articles.clear(); + m_articles.clear(); } -void FileInfo::SetID(int iID) +void FileInfo::SetID(int id) { - m_iID = iID; - if (m_iIDMax < m_iID) + m_id = id; + if (m_idMax < m_id) { - m_iIDMax = m_iID; + m_idMax = m_id; } } -void FileInfo::ResetGenID(bool bMax) +void FileInfo::ResetGenID(bool max) { - if (bMax) + if (max) { - m_iIDGen = m_iIDMax; + m_idGen = m_idMax; } else { - m_iIDGen = 0; - m_iIDMax = 0; + m_idGen = 0; + m_idMax = 0; } } -void FileInfo::SetPaused(bool bPaused) +void FileInfo::SetPaused(bool paused) { - if (m_bPaused != bPaused && m_pNZBInfo) + if (m_paused != paused && m_nzbInfo) { - m_pNZBInfo->SetPausedFileCount(m_pNZBInfo->GetPausedFileCount() + (bPaused ? 1 : -1)); - m_pNZBInfo->SetPausedSize(m_pNZBInfo->GetPausedSize() + (bPaused ? m_lRemainingSize : - m_lRemainingSize)); + m_nzbInfo->SetPausedFileCount(m_nzbInfo->GetPausedFileCount() + (paused ? 1 : -1)); + m_nzbInfo->SetPausedSize(m_nzbInfo->GetPausedSize() + (paused ? m_remainingSize : - m_remainingSize)); } - m_bPaused = bPaused; + m_paused = paused; } -void FileInfo::SetSubject(const char* szSubject) +void FileInfo::SetSubject(const char* subject) { - m_szSubject = strdup(szSubject); + m_subject = strdup(subject); } -void FileInfo::SetFilename(const char* szFilename) +void FileInfo::SetFilename(const char* filename) { - free(m_szFilename); - m_szFilename = strdup(szFilename); + free(m_filename); + m_filename = strdup(filename); } void FileInfo::MakeValidFilename() { - Util::MakeValidFilename(m_szFilename, '_', false); + Util::MakeValidFilename(m_filename, '_', false); } void FileInfo::LockOutputFile() { - m_pMutexOutputFile->Lock(); + m_mutexOutputFile->Lock(); } void FileInfo::UnlockOutputFile() { - m_pMutexOutputFile->Unlock(); + m_mutexOutputFile->Unlock(); } -void FileInfo::SetOutputFilename(const char* szOutputFilename) +void FileInfo::SetOutputFilename(const char* outputFilename) { - free(m_szOutputFilename); - m_szOutputFilename = strdup(szOutputFilename); + free(m_outputFilename); + m_outputFilename = strdup(outputFilename); } -void FileInfo::SetActiveDownloads(int iActiveDownloads) +void FileInfo::SetActiveDownloads(int activeDownloads) { - m_iActiveDownloads = iActiveDownloads; + m_activeDownloads = activeDownloads; - if (m_iActiveDownloads > 0 && !m_pMutexOutputFile) + if (m_activeDownloads > 0 && !m_mutexOutputFile) { - m_pMutexOutputFile = new Mutex(); + m_mutexOutputFile = new Mutex(); } - else if (m_iActiveDownloads == 0 && m_pMutexOutputFile) + else if (m_activeDownloads == 0 && m_mutexOutputFile) { - delete m_pMutexOutputFile; - m_pMutexOutputFile = NULL; + delete m_mutexOutputFile; + m_mutexOutputFile = NULL; } } FileList::~FileList() { - if (m_bOwnObjects) + if (m_ownObjects) { Clear(); } @@ -1229,172 +1229,172 @@ void FileList::Clear() clear(); } -void FileList::Remove(FileInfo* pFileInfo) +void FileList::Remove(FileInfo* fileInfo) { - erase(std::find(begin(), end(), pFileInfo)); + erase(std::find(begin(), end(), fileInfo)); } -CompletedFile::CompletedFile(int iID, const char* szFileName, EStatus eStatus, unsigned long lCrc) +CompletedFile::CompletedFile(int id, const char* fileName, EStatus status, unsigned long crc) { - m_iID = iID; + m_id = id; - if (FileInfo::m_iIDMax < m_iID) + if (FileInfo::m_idMax < m_id) { - FileInfo::m_iIDMax = m_iID; + FileInfo::m_idMax = m_id; } - m_szFileName = strdup(szFileName); - m_eStatus = eStatus; - m_lCrc = lCrc; + m_fileName = strdup(fileName); + m_status = status; + m_crc = crc; } -void CompletedFile::SetFileName(const char* szFileName) +void CompletedFile::SetFileName(const char* fileName) { - free(m_szFileName); - m_szFileName = strdup(szFileName); + free(m_fileName); + m_fileName = strdup(fileName); } CompletedFile::~CompletedFile() { - free(m_szFileName); + free(m_fileName); } PostInfo::PostInfo() { debug("Creating PostInfo"); - m_pNZBInfo = NULL; - m_bWorking = false; - m_bDeleted = false; - m_bRequestParCheck = false; - m_bForceParFull = false; - m_bForceRepair = false; - m_bParRepaired = false; - m_bUnpackTried = false; - m_bPassListTried = false; - m_eLastUnpackStatus = 0; - m_szProgressLabel = strdup(""); - m_iFileProgress = 0; - m_iStageProgress = 0; - m_tStartTime = 0; - m_tStageTime = 0; - m_eStage = ptQueued; - m_pPostThread = NULL; + m_nzbInfo = NULL; + m_working = false; + m_deleted = false; + m_requestParCheck = false; + m_forceParFull = false; + m_forceRepair = false; + m_parRepaired = false; + m_unpackTried = false; + m_passListTried = false; + m_lastUnpackStatus = 0; + m_progressLabel = strdup(""); + m_fileProgress = 0; + m_stageProgress = 0; + m_startTime = 0; + m_stageTime = 0; + m_stage = ptQueued; + m_postThread = NULL; } PostInfo::~ PostInfo() { debug("Destroying PostInfo"); - free(m_szProgressLabel); + free(m_progressLabel); - for (ParredFiles::iterator it = m_ParredFiles.begin(); it != m_ParredFiles.end(); it++) + for (ParredFiles::iterator it = m_parredFiles.begin(); it != m_parredFiles.end(); it++) { free(*it); } } -void PostInfo::SetProgressLabel(const char* szProgressLabel) +void PostInfo::SetProgressLabel(const char* progressLabel) { - free(m_szProgressLabel); - m_szProgressLabel = strdup(szProgressLabel); + free(m_progressLabel); + m_progressLabel = strdup(progressLabel); } DupInfo::DupInfo() { - m_iID = 0; - m_szName = NULL; - m_szDupeKey = NULL; - m_iDupeScore = 0; - m_eDupeMode = dmScore; - m_lSize = 0; - m_iFullContentHash = 0; - m_iFilteredContentHash = 0; - m_eStatus = dsUndefined; + m_id = 0; + m_name = NULL; + m_dupeKey = NULL; + m_dupeScore = 0; + m_dupeMode = dmScore; + m_size = 0; + m_fullContentHash = 0; + m_filteredContentHash = 0; + m_status = dsUndefined; } DupInfo::~DupInfo() { - free(m_szName); - free(m_szDupeKey); + free(m_name); + free(m_dupeKey); } -void DupInfo::SetID(int iID) +void DupInfo::SetID(int id) { - m_iID = iID; - if (NZBInfo::m_iIDMax < m_iID) + m_id = id; + if (NZBInfo::m_idMax < m_id) { - NZBInfo::m_iIDMax = m_iID; + NZBInfo::m_idMax = m_id; } } -void DupInfo::SetName(const char* szName) +void DupInfo::SetName(const char* name) { - free(m_szName); - m_szName = strdup(szName); + free(m_name); + m_name = strdup(name); } -void DupInfo::SetDupeKey(const char* szDupeKey) +void DupInfo::SetDupeKey(const char* dupeKey) { - free(m_szDupeKey); - m_szDupeKey = strdup(szDupeKey); + free(m_dupeKey); + m_dupeKey = strdup(dupeKey); } -HistoryInfo::HistoryInfo(NZBInfo* pNZBInfo) +HistoryInfo::HistoryInfo(NZBInfo* nzbInfo) { - m_eKind = pNZBInfo->GetKind() == NZBInfo::nkNzb ? hkNzb : hkUrl; - m_pInfo = pNZBInfo; - m_tTime = 0; + m_kind = nzbInfo->GetKind() == NZBInfo::nkNzb ? hkNzb : hkUrl; + m_info = nzbInfo; + m_time = 0; } -HistoryInfo::HistoryInfo(DupInfo* pDupInfo) +HistoryInfo::HistoryInfo(DupInfo* dupInfo) { - m_eKind = hkDup; - m_pInfo = pDupInfo; - m_tTime = 0; + m_kind = hkDup; + m_info = dupInfo; + m_time = 0; } HistoryInfo::~HistoryInfo() { - if ((m_eKind == hkNzb || m_eKind == hkUrl) && m_pInfo) + if ((m_kind == hkNzb || m_kind == hkUrl) && m_info) { - delete (NZBInfo*)m_pInfo; + delete (NZBInfo*)m_info; } - else if (m_eKind == hkDup && m_pInfo) + else if (m_kind == hkDup && m_info) { - delete (DupInfo*)m_pInfo; + delete (DupInfo*)m_info; } } int HistoryInfo::GetID() { - if ((m_eKind == hkNzb || m_eKind == hkUrl)) + if ((m_kind == hkNzb || m_kind == hkUrl)) { - return ((NZBInfo*)m_pInfo)->GetID(); + return ((NZBInfo*)m_info)->GetID(); } else // if (m_eKind == hkDup) { - return ((DupInfo*)m_pInfo)->GetID(); + return ((DupInfo*)m_info)->GetID(); } } -void HistoryInfo::GetName(char* szBuffer, int iSize) +void HistoryInfo::GetName(char* buffer, int size) { - if (m_eKind == hkNzb || m_eKind == hkUrl) + if (m_kind == hkNzb || m_kind == hkUrl) { - strncpy(szBuffer, GetNZBInfo()->GetName(), iSize); - szBuffer[iSize-1] = '\0'; + strncpy(buffer, GetNZBInfo()->GetName(), size); + buffer[size-1] = '\0'; } - else if (m_eKind == hkDup) + else if (m_kind == hkDup) { - strncpy(szBuffer, GetDupInfo()->GetName(), iSize); - szBuffer[iSize-1] = '\0'; + strncpy(buffer, GetDupInfo()->GetName(), size); + buffer[size-1] = '\0'; } else { - strncpy(szBuffer, "", iSize); + strncpy(buffer, "", size); } } @@ -1407,14 +1407,14 @@ HistoryList::~HistoryList() } } -HistoryInfo* HistoryList::Find(int iID) +HistoryInfo* HistoryList::Find(int id) { for (iterator it = begin(); it != end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetID() == iID) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetID() == id) { - return pHistoryInfo; + return historyInfo; } } @@ -1424,41 +1424,41 @@ HistoryInfo* HistoryList::Find(int iID) DownloadQueue* DownloadQueue::Lock() { - g_pDownloadQueue->m_LockMutex.Lock(); + g_pDownloadQueue->m_lockMutex.Lock(); return g_pDownloadQueue; } void DownloadQueue::Unlock() { - g_pDownloadQueue->m_LockMutex.Unlock(); + g_pDownloadQueue->m_lockMutex.Unlock(); } -void DownloadQueue::CalcRemainingSize(long long* pRemaining, long long* pRemainingForced) +void DownloadQueue::CalcRemainingSize(long long* remaining, long long* remainingForced) { - long long lRemainingSize = 0; - long long lRemainingForced = 0; + long long remainingSize = 0; + long long remainingForcedSize = 0; - for (NZBList::iterator it = m_Queue.begin(); it != m_Queue.end(); it++) + for (NZBList::iterator it = m_queue.begin(); it != m_queue.end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - if (!pFileInfo->GetPaused() && !pFileInfo->GetDeleted()) + FileInfo* fileInfo = *it2; + if (!fileInfo->GetPaused() && !fileInfo->GetDeleted()) { - lRemainingSize += pFileInfo->GetRemainingSize(); - if (pNZBInfo->GetForcePriority()) + remainingSize += fileInfo->GetRemainingSize(); + if (nzbInfo->GetForcePriority()) { - lRemainingForced += pFileInfo->GetRemainingSize(); + remainingForcedSize += fileInfo->GetRemainingSize(); } } } } - *pRemaining = lRemainingSize; + *remaining = remainingSize; - if (pRemainingForced) + if (remainingForced) { - *pRemainingForced = lRemainingForced; + *remainingForced = remainingForcedSize; } } diff --git a/daemon/queue/DownloadInfo.h b/daemon/queue/DownloadInfo.h index 14f4ee1d..b3df1cca 100644 --- a/daemon/queue/DownloadInfo.h +++ b/daemon/queue/DownloadInfo.h @@ -42,17 +42,17 @@ class PostInfo; class ServerStat { private: - int m_iServerID; - int m_iSuccessArticles; - int m_iFailedArticles; + int m_serverId; + int m_successArticles; + int m_failedArticles; public: - ServerStat(int iServerID); - int GetServerID() { return m_iServerID; } - int GetSuccessArticles() { return m_iSuccessArticles; } - void SetSuccessArticles(int iSuccessArticles) { m_iSuccessArticles = iSuccessArticles; } - int GetFailedArticles() { return m_iFailedArticles; } - void SetFailedArticles(int iFailedArticles) { m_iFailedArticles = iFailedArticles; } + ServerStat(int serverId); + int GetServerID() { return m_serverId; } + int GetSuccessArticles() { return m_successArticles; } + void SetSuccessArticles(int successArticles) { m_successArticles = successArticles; } + int GetFailedArticles() { return m_failedArticles; } + void SetFailedArticles(int failedArticles) { m_failedArticles = failedArticles; } }; typedef std::vector ServerStatListBase; @@ -69,8 +69,8 @@ public: public: ~ServerStatList(); - void StatOp(int iServerID, int iSuccessArticles, int iFailedArticles, EStatOperation eStatOperation); - void ListOp(ServerStatList* pServerStats, EStatOperation eStatOperation); + void StatOp(int serverId, int successArticles, int failedArticles, EStatOperation statOperation); + void ListOp(ServerStatList* serverStats, EStatOperation statOperation); void Clear(); }; @@ -86,38 +86,38 @@ public: }; private: - int m_iPartNumber; - char* m_szMessageID; - int m_iSize; - char* m_pSegmentContent; - long long m_iSegmentOffset; - int m_iSegmentSize; - EStatus m_eStatus; - char* m_szResultFilename; - unsigned long m_lCrc; + int m_partNumber; + char* m_messageId; + int m_size; + char* m_segmentContent; + long long m_segmentOffset; + int m_segmentSize; + EStatus m_status; + char* m_resultFilename; + unsigned long m_crc; public: ArticleInfo(); ~ArticleInfo(); - void SetPartNumber(int s) { m_iPartNumber = s; } - int GetPartNumber() { return m_iPartNumber; } - const char* GetMessageID() { return m_szMessageID; } - void SetMessageID(const char* szMessageID); - void SetSize(int iSize) { m_iSize = iSize; } - int GetSize() { return m_iSize; } - void AttachSegment(char* pContent, long long iOffset, int iSize); + void SetPartNumber(int s) { m_partNumber = s; } + int GetPartNumber() { return m_partNumber; } + const char* GetMessageID() { return m_messageId; } + void SetMessageID(const char* messageId); + void SetSize(int size) { m_size = size; } + int GetSize() { return m_size; } + void AttachSegment(char* content, long long offset, int size); void DiscardSegment(); - const char* GetSegmentContent() { return m_pSegmentContent; } - void SetSegmentOffset(long long iSegmentOffset) { m_iSegmentOffset = iSegmentOffset; } - long long GetSegmentOffset() { return m_iSegmentOffset; } - void SetSegmentSize(int iSegmentSize) { m_iSegmentSize = iSegmentSize; } - int GetSegmentSize() { return m_iSegmentSize; } - EStatus GetStatus() { return m_eStatus; } - void SetStatus(EStatus Status) { m_eStatus = Status; } - const char* GetResultFilename() { return m_szResultFilename; } + const char* GetSegmentContent() { return m_segmentContent; } + void SetSegmentOffset(long long segmentOffset) { m_segmentOffset = segmentOffset; } + long long GetSegmentOffset() { return m_segmentOffset; } + void SetSegmentSize(int segmentSize) { m_segmentSize = segmentSize; } + int GetSegmentSize() { return m_segmentSize; } + EStatus GetStatus() { return m_status; } + void SetStatus(EStatus Status) { m_status = Status; } + const char* GetResultFilename() { return m_resultFilename; } void SetResultFilename(const char* v); - unsigned long GetCrc() { return m_lCrc; } - void SetCrc(unsigned long lCrc) { m_lCrc = lCrc; } + unsigned long GetCrc() { return m_crc; } + void SetCrc(unsigned long crc) { m_crc = crc; } }; class FileInfo @@ -127,105 +127,105 @@ public: typedef std::vector Groups; private: - int m_iID; - NZBInfo* m_pNZBInfo; - Articles m_Articles; - Groups m_Groups; - ServerStatList m_ServerStats; - char* m_szSubject; - char* m_szFilename; - long long m_lSize; - long long m_lRemainingSize; - long long m_lSuccessSize; - long long m_lFailedSize; - long long m_lMissedSize; - int m_iTotalArticles; - int m_iMissedArticles; - int m_iFailedArticles; - int m_iSuccessArticles; - time_t m_tTime; - bool m_bPaused; - bool m_bDeleted; - bool m_bFilenameConfirmed; - bool m_bParFile; - int m_iCompletedArticles; - bool m_bOutputInitialized; - char* m_szOutputFilename; - Mutex* m_pMutexOutputFile; - bool m_bExtraPriority; - int m_iActiveDownloads; - bool m_bAutoDeleted; - int m_iCachedArticles; - bool m_bPartialChanged; + int m_id; + NZBInfo* m_nzbInfo; + Articles m_articles; + Groups m_groups; + ServerStatList m_serverStats; + char* m_subject; + char* m_filename; + long long m_size; + long long m_remainingSize; + long long m_successSize; + long long m_failedSize; + long long m_missedSize; + int m_totalArticles; + int m_missedArticles; + int m_failedArticles; + int m_successArticles; + time_t m_time; + bool m_paused; + bool m_deleted; + bool m_filenameConfirmed; + bool m_parFile; + int m_completedArticles; + bool m_outputInitialized; + char* m_outputFilename; + Mutex* m_mutexOutputFile; + bool m_extraPriority; + int m_activeDownloads; + bool m_autoDeleted; + int m_cachedArticles; + bool m_partialChanged; - static int m_iIDGen; - static int m_iIDMax; + static int m_idGen; + static int m_idMax; friend class CompletedFile; public: - FileInfo(int iID = 0); + FileInfo(int id = 0); ~FileInfo(); - int GetID() { return m_iID; } - void SetID(int iID); - static void ResetGenID(bool bMax); - NZBInfo* GetNZBInfo() { return m_pNZBInfo; } - void SetNZBInfo(NZBInfo* pNZBInfo) { m_pNZBInfo = pNZBInfo; } - Articles* GetArticles() { return &m_Articles; } - Groups* GetGroups() { return &m_Groups; } - const char* GetSubject() { return m_szSubject; } - void SetSubject(const char* szSubject); - const char* GetFilename() { return m_szFilename; } - void SetFilename(const char* szFilename); + int GetID() { return m_id; } + void SetID(int id); + static void ResetGenID(bool max); + NZBInfo* GetNZBInfo() { return m_nzbInfo; } + void SetNZBInfo(NZBInfo* nzbInfo) { m_nzbInfo = nzbInfo; } + Articles* GetArticles() { return &m_articles; } + Groups* GetGroups() { return &m_groups; } + const char* GetSubject() { return m_subject; } + void SetSubject(const char* subject); + const char* GetFilename() { return m_filename; } + void SetFilename(const char* filename); void MakeValidFilename(); - bool GetFilenameConfirmed() { return m_bFilenameConfirmed; } - void SetFilenameConfirmed(bool bFilenameConfirmed) { m_bFilenameConfirmed = bFilenameConfirmed; } - void SetSize(long long lSize) { m_lSize = lSize; m_lRemainingSize = lSize; } - long long GetSize() { return m_lSize; } - long long GetRemainingSize() { return m_lRemainingSize; } - void SetRemainingSize(long long lRemainingSize) { m_lRemainingSize = lRemainingSize; } - long long GetMissedSize() { return m_lMissedSize; } - void SetMissedSize(long long lMissedSize) { m_lMissedSize = lMissedSize; } - long long GetSuccessSize() { return m_lSuccessSize; } - void SetSuccessSize(long long lSuccessSize) { m_lSuccessSize = lSuccessSize; } - long long GetFailedSize() { return m_lFailedSize; } - void SetFailedSize(long long lFailedSize) { m_lFailedSize = lFailedSize; } - int GetTotalArticles() { return m_iTotalArticles; } - void SetTotalArticles(int iTotalArticles) { m_iTotalArticles = iTotalArticles; } - int GetMissedArticles() { return m_iMissedArticles; } - void SetMissedArticles(int iMissedArticles) { m_iMissedArticles = iMissedArticles; } - int GetFailedArticles() { return m_iFailedArticles; } - void SetFailedArticles(int iFailedArticles) { m_iFailedArticles = iFailedArticles; } - int GetSuccessArticles() { return m_iSuccessArticles; } - void SetSuccessArticles(int iSuccessArticles) { m_iSuccessArticles = iSuccessArticles; } - time_t GetTime() { return m_tTime; } - void SetTime(time_t tTime) { m_tTime = tTime; } - bool GetPaused() { return m_bPaused; } - void SetPaused(bool bPaused); - bool GetDeleted() { return m_bDeleted; } - void SetDeleted(bool Deleted) { m_bDeleted = Deleted; } - int GetCompletedArticles() { return m_iCompletedArticles; } - void SetCompletedArticles(int iCompletedArticles) { m_iCompletedArticles = iCompletedArticles; } - bool GetParFile() { return m_bParFile; } - void SetParFile(bool bParFile) { m_bParFile = bParFile; } + bool GetFilenameConfirmed() { return m_filenameConfirmed; } + void SetFilenameConfirmed(bool filenameConfirmed) { m_filenameConfirmed = filenameConfirmed; } + void SetSize(long long size) { m_size = size; m_remainingSize = size; } + long long GetSize() { return m_size; } + long long GetRemainingSize() { return m_remainingSize; } + void SetRemainingSize(long long remainingSize) { m_remainingSize = remainingSize; } + long long GetMissedSize() { return m_missedSize; } + void SetMissedSize(long long missedSize) { m_missedSize = missedSize; } + long long GetSuccessSize() { return m_successSize; } + void SetSuccessSize(long long successSize) { m_successSize = successSize; } + long long GetFailedSize() { return m_failedSize; } + void SetFailedSize(long long failedSize) { m_failedSize = failedSize; } + int GetTotalArticles() { return m_totalArticles; } + void SetTotalArticles(int totalArticles) { m_totalArticles = totalArticles; } + int GetMissedArticles() { return m_missedArticles; } + void SetMissedArticles(int missedArticles) { m_missedArticles = missedArticles; } + int GetFailedArticles() { return m_failedArticles; } + void SetFailedArticles(int failedArticles) { m_failedArticles = failedArticles; } + int GetSuccessArticles() { return m_successArticles; } + void SetSuccessArticles(int successArticles) { m_successArticles = successArticles; } + time_t GetTime() { return m_time; } + void SetTime(time_t time) { m_time = time; } + bool GetPaused() { return m_paused; } + void SetPaused(bool paused); + bool GetDeleted() { return m_deleted; } + void SetDeleted(bool Deleted) { m_deleted = Deleted; } + int GetCompletedArticles() { return m_completedArticles; } + void SetCompletedArticles(int completedArticles) { m_completedArticles = completedArticles; } + bool GetParFile() { return m_parFile; } + void SetParFile(bool parFile) { m_parFile = parFile; } void ClearArticles(); void LockOutputFile(); void UnlockOutputFile(); - const char* GetOutputFilename() { return m_szOutputFilename; } - void SetOutputFilename(const char* szOutputFilename); - bool GetOutputInitialized() { return m_bOutputInitialized; } - void SetOutputInitialized(bool bOutputInitialized) { m_bOutputInitialized = bOutputInitialized; } - bool GetExtraPriority() { return m_bExtraPriority; } - void SetExtraPriority(bool bExtraPriority) { m_bExtraPriority = bExtraPriority; } - int GetActiveDownloads() { return m_iActiveDownloads; } - void SetActiveDownloads(int iActiveDownloads); - bool GetAutoDeleted() { return m_bAutoDeleted; } - void SetAutoDeleted(bool bAutoDeleted) { m_bAutoDeleted = bAutoDeleted; } - int GetCachedArticles() { return m_iCachedArticles; } - void SetCachedArticles(int iCachedArticles) { m_iCachedArticles = iCachedArticles; } - bool GetPartialChanged() { return m_bPartialChanged; } - void SetPartialChanged(bool bPartialChanged) { m_bPartialChanged = bPartialChanged; } - ServerStatList* GetServerStats() { return &m_ServerStats; } + const char* GetOutputFilename() { return m_outputFilename; } + void SetOutputFilename(const char* outputFilename); + bool GetOutputInitialized() { return m_outputInitialized; } + void SetOutputInitialized(bool outputInitialized) { m_outputInitialized = outputInitialized; } + bool GetExtraPriority() { return m_extraPriority; } + void SetExtraPriority(bool extraPriority) { m_extraPriority = extraPriority; } + int GetActiveDownloads() { return m_activeDownloads; } + void SetActiveDownloads(int activeDownloads); + bool GetAutoDeleted() { return m_autoDeleted; } + void SetAutoDeleted(bool autoDeleted) { m_autoDeleted = autoDeleted; } + int GetCachedArticles() { return m_cachedArticles; } + void SetCachedArticles(int cachedArticles) { m_cachedArticles = cachedArticles; } + bool GetPartialChanged() { return m_partialChanged; } + void SetPartialChanged(bool partialChanged) { m_partialChanged = partialChanged; } + ServerStatList* GetServerStats() { return &m_serverStats; } }; typedef std::deque FileListBase; @@ -233,12 +233,12 @@ typedef std::deque FileListBase; class FileList : public FileListBase { private: - bool m_bOwnObjects; + bool m_ownObjects; public: - FileList(bool bOwnObjects = false) { m_bOwnObjects = bOwnObjects; } + FileList(bool ownObjects = false) { m_ownObjects = ownObjects; } ~FileList(); void Clear(); - void Remove(FileInfo* pFileInfo); + void Remove(FileInfo* fileInfo); }; class CompletedFile @@ -253,19 +253,19 @@ public: }; private: - int m_iID; - char* m_szFileName; - EStatus m_eStatus; - unsigned long m_lCrc; + int m_id; + char* m_fileName; + EStatus m_status; + unsigned long m_crc; public: - CompletedFile(int iID, const char* szFileName, EStatus eStatus, unsigned long lCrc); + CompletedFile(int id, const char* fileName, EStatus status, unsigned long crc); ~CompletedFile(); - int GetID() { return m_iID; } - void SetFileName(const char* szFileName); - const char* GetFileName() { return m_szFileName; } - EStatus GetStatus() { return m_eStatus; } - unsigned long GetCrc() { return m_lCrc; } + int GetID() { return m_id; } + void SetFileName(const char* fileName); + const char* GetFileName() { return m_fileName; } + EStatus GetStatus() { return m_status; } + unsigned long GetCrc() { return m_crc; } }; typedef std::deque CompletedFiles; @@ -273,18 +273,18 @@ typedef std::deque CompletedFiles; class NZBParameter { private: - char* m_szName; - char* m_szValue; + char* m_name; + char* m_value; - void SetValue(const char* szValue); + void SetValue(const char* value); friend class NZBParameterList; public: - NZBParameter(const char* szName); + NZBParameter(const char* name); ~NZBParameter(); - const char* GetName() { return m_szName; } - const char* GetValue() { return m_szValue; } + const char* GetName() { return m_name; } + const char* GetValue() { return m_value; } }; typedef std::deque NZBParameterListBase; @@ -293,10 +293,10 @@ class NZBParameterList : public NZBParameterListBase { public: ~NZBParameterList(); - void SetParameter(const char* szName, const char* szValue); - NZBParameter* Find(const char* szName, bool bCaseSensitive); + void SetParameter(const char* name, const char* value); + NZBParameter* Find(const char* name, bool caseSensitive); void Clear(); - void CopyFrom(NZBParameterList* pSourceParameters); + void CopyFrom(NZBParameterList* sourceParameters); }; class ScriptStatus @@ -310,16 +310,16 @@ public: }; private: - char* m_szName; - EStatus m_eStatus; + char* m_name; + EStatus m_status; friend class ScriptStatusList; public: - ScriptStatus(const char* szName, EStatus eStatus); + ScriptStatus(const char* name, EStatus status); ~ScriptStatus(); - const char* GetName() { return m_szName; } - EStatus GetStatus() { return m_eStatus; } + const char* GetName() { return m_name; } + EStatus GetStatus() { return m_status; } }; typedef std::deque ScriptStatusListBase; @@ -328,7 +328,7 @@ class ScriptStatusList : public ScriptStatusListBase { public: ~ScriptStatusList(); - void Add(const char* szScriptName, ScriptStatus::EStatus eStatus); + void Add(const char* scriptName, ScriptStatus::EStatus status); void Clear(); ScriptStatus::EStatus CalcTotalStatus(); }; @@ -427,262 +427,262 @@ public: friend class DupInfo; private: - int m_iID; - EKind m_eKind; - char* m_szURL; - char* m_szFilename; - char* m_szName; - char* m_szDestDir; - char* m_szFinalDir; - char* m_szCategory; - int m_iFileCount; - int m_iParkedFileCount; - long long m_lSize; - long long m_lRemainingSize; - int m_iPausedFileCount; - long long m_lPausedSize; - int m_iRemainingParCount; - int m_iActiveDownloads; - long long m_lSuccessSize; - long long m_lFailedSize; - long long m_lCurrentSuccessSize; - long long m_lCurrentFailedSize; - long long m_lParSize; - long long m_lParSuccessSize; - long long m_lParFailedSize; - long long m_lParCurrentSuccessSize; - long long m_lParCurrentFailedSize; - int m_iTotalArticles; - int m_iSuccessArticles; - int m_iFailedArticles; - int m_iCurrentSuccessArticles; - int m_iCurrentFailedArticles; - time_t m_tMinTime; - time_t m_tMaxTime; - int m_iPriority; + int m_id; + EKind m_kind; + char* m_url; + char* m_filename; + char* m_name; + char* m_destDir; + char* m_finalDir; + char* m_category; + int m_fileCount; + int m_parkedFileCount; + long long m_size; + long long m_remainingSize; + int m_pausedFileCount; + long long m_pausedSize; + int m_remainingParCount; + int m_activeDownloads; + long long m_successSize; + long long m_failedSize; + long long m_currentSuccessSize; + long long m_currentFailedSize; + long long m_parSize; + long long m_parSuccessSize; + long long m_parFailedSize; + long long m_parCurrentSuccessSize; + long long m_parCurrentFailedSize; + int m_totalArticles; + int m_successArticles; + int m_failedArticles; + int m_currentSuccessArticles; + int m_currentFailedArticles; + time_t m_minTime; + time_t m_maxTime; + int m_priority; CompletedFiles m_completedFiles; - ERenameStatus m_eRenameStatus; - EParStatus m_eParStatus; - EUnpackStatus m_eUnpackStatus; - ECleanupStatus m_eCleanupStatus; - EMoveStatus m_eMoveStatus; - EDeleteStatus m_eDeleteStatus; - EMarkStatus m_eMarkStatus; - EUrlStatus m_eUrlStatus; - int m_iExtraParBlocks; - bool m_bAddUrlPaused; - bool m_bDeletePaused; - bool m_bManyDupeFiles; - char* m_szQueuedFilename; - bool m_bDeleting; - bool m_bAvoidHistory; - bool m_bHealthPaused; - bool m_bParCleanup; - bool m_bParManual; - bool m_bCleanupDisk; - bool m_bUnpackCleanedUpDisk; - char* m_szDupeKey; - int m_iDupeScore; - EDupeMode m_eDupeMode; - unsigned int m_iFullContentHash; - unsigned int m_iFilteredContentHash; - FileList m_FileList; + ERenameStatus m_renameStatus; + EParStatus m_parStatus; + EUnpackStatus m_unpackStatus; + ECleanupStatus m_cleanupStatus; + EMoveStatus m_moveStatus; + EDeleteStatus m_deleteStatus; + EMarkStatus m_markStatus; + EUrlStatus m_urlStatus; + int m_extraParBlocks; + bool m_addUrlPaused; + bool m_deletePaused; + bool m_manyDupeFiles; + char* m_queuedFilename; + bool m_deleting; + bool m_avoidHistory; + bool m_healthPaused; + bool m_parCleanup; + bool m_parManual; + bool m_cleanupDisk; + bool m_unpackCleanedUpDisk; + char* m_dupeKey; + int m_dupeScore; + EDupeMode m_dupeMode; + unsigned int m_fullContentHash; + unsigned int m_filteredContentHash; + FileList m_fileList; NZBParameterList m_ppParameters; ScriptStatusList m_scriptStatuses; - ServerStatList m_ServerStats; - ServerStatList m_CurrentServerStats; - Mutex m_mutexLog; - MessageList m_Messages; - int m_iIDMessageGen; - PostInfo* m_pPostInfo; - long long m_lDownloadedSize; - time_t m_tDownloadStartTime; - int m_iDownloadSec; - int m_iPostTotalSec; - int m_iParSec; - int m_iRepairSec; - int m_iUnpackSec; - bool m_bReprocess; - time_t m_tQueueScriptTime; - bool m_bParFull; - int m_iMessageCount; - int m_iCachedMessageCount; - int m_iFeedID; + ServerStatList m_serverStats; + ServerStatList m_currentServerStats; + Mutex m_logMutex; + MessageList m_messages; + int m_idMessageGen; + PostInfo* m_postInfo; + long long m_downloadedSize; + time_t m_downloadStartTime; + int m_downloadSec; + int m_postTotalSec; + int m_parSec; + int m_repairSec; + int m_unpackSec; + bool m_reprocess; + time_t m_queueScriptTime; + bool m_parFull; + int m_messageCount; + int m_cachedMessageCount; + int m_feedId; - static int m_iIDGen; - static int m_iIDMax; + static int m_idGen; + static int m_idMax; void ClearMessages(); public: NZBInfo(); ~NZBInfo(); - int GetID() { return m_iID; } - void SetID(int iID); - static void ResetGenID(bool bMax); + int GetID() { return m_id; } + void SetID(int id); + static void ResetGenID(bool max); static int GenerateID(); - EKind GetKind() { return m_eKind; } - void SetKind(EKind eKind) { m_eKind = eKind; } - const char* GetURL() { return m_szURL; } // needs locking (for shared objects) - void SetURL(const char* szURL); // needs locking (for shared objects) - const char* GetFilename() { return m_szFilename; } - void SetFilename(const char* szFilename); - static void MakeNiceNZBName(const char* szNZBFilename, char* szBuffer, int iSize, bool bRemoveExt); - static void MakeNiceUrlName(const char* szURL, const char* szNZBFilename, char* szBuffer, int iSize); - const char* GetDestDir() { return m_szDestDir; } // needs locking (for shared objects) - void SetDestDir(const char* szDestDir); // needs locking (for shared objects) - const char* GetFinalDir() { return m_szFinalDir; } // needs locking (for shared objects) - void SetFinalDir(const char* szFinalDir); // needs locking (for shared objects) - const char* GetCategory() { return m_szCategory; } // needs locking (for shared objects) - void SetCategory(const char* szCategory); // needs locking (for shared objects) - const char* GetName() { return m_szName; } // needs locking (for shared objects) - void SetName(const char* szName); // needs locking (for shared objects) - int GetFileCount() { return m_iFileCount; } - void SetFileCount(int iFileCount) { m_iFileCount = iFileCount; } - int GetParkedFileCount() { return m_iParkedFileCount; } - void SetParkedFileCount(int iParkedFileCount) { m_iParkedFileCount = iParkedFileCount; } - long long GetSize() { return m_lSize; } - void SetSize(long long lSize) { m_lSize = lSize; } - long long GetRemainingSize() { return m_lRemainingSize; } - void SetRemainingSize(long long lRemainingSize) { m_lRemainingSize = lRemainingSize; } - long long GetPausedSize() { return m_lPausedSize; } - void SetPausedSize(long long lPausedSize) { m_lPausedSize = lPausedSize; } - int GetPausedFileCount() { return m_iPausedFileCount; } - void SetPausedFileCount(int iPausedFileCount) { m_iPausedFileCount = iPausedFileCount; } - int GetRemainingParCount() { return m_iRemainingParCount; } - void SetRemainingParCount(int iRemainingParCount) { m_iRemainingParCount = iRemainingParCount; } - int GetActiveDownloads() { return m_iActiveDownloads; } - void SetActiveDownloads(int iActiveDownloads); - long long GetSuccessSize() { return m_lSuccessSize; } - void SetSuccessSize(long long lSuccessSize) { m_lSuccessSize = lSuccessSize; } - long long GetFailedSize() { return m_lFailedSize; } - void SetFailedSize(long long lFailedSize) { m_lFailedSize = lFailedSize; } - long long GetCurrentSuccessSize() { return m_lCurrentSuccessSize; } - void SetCurrentSuccessSize(long long lCurrentSuccessSize) { m_lCurrentSuccessSize = lCurrentSuccessSize; } - long long GetCurrentFailedSize() { return m_lCurrentFailedSize; } - void SetCurrentFailedSize(long long lCurrentFailedSize) { m_lCurrentFailedSize = lCurrentFailedSize; } - long long GetParSize() { return m_lParSize; } - void SetParSize(long long lParSize) { m_lParSize = lParSize; } - long long GetParSuccessSize() { return m_lParSuccessSize; } - void SetParSuccessSize(long long lParSuccessSize) { m_lParSuccessSize = lParSuccessSize; } - long long GetParFailedSize() { return m_lParFailedSize; } - void SetParFailedSize(long long lParFailedSize) { m_lParFailedSize = lParFailedSize; } - long long GetParCurrentSuccessSize() { return m_lParCurrentSuccessSize; } - void SetParCurrentSuccessSize(long long lParCurrentSuccessSize) { m_lParCurrentSuccessSize = lParCurrentSuccessSize; } - long long GetParCurrentFailedSize() { return m_lParCurrentFailedSize; } - void SetParCurrentFailedSize(long long lParCurrentFailedSize) { m_lParCurrentFailedSize = lParCurrentFailedSize; } - int GetTotalArticles() { return m_iTotalArticles; } - void SetTotalArticles(int iTotalArticles) { m_iTotalArticles = iTotalArticles; } - int GetSuccessArticles() { return m_iSuccessArticles; } - void SetSuccessArticles(int iSuccessArticles) { m_iSuccessArticles = iSuccessArticles; } - int GetFailedArticles() { return m_iFailedArticles; } - void SetFailedArticles(int iFailedArticles) { m_iFailedArticles = iFailedArticles; } - int GetCurrentSuccessArticles() { return m_iCurrentSuccessArticles; } - void SetCurrentSuccessArticles(int iCurrentSuccessArticles) { m_iCurrentSuccessArticles = iCurrentSuccessArticles; } - int GetCurrentFailedArticles() { return m_iCurrentFailedArticles; } - void SetCurrentFailedArticles(int iCurrentFailedArticles) { m_iCurrentFailedArticles = iCurrentFailedArticles; } - int GetPriority() { return m_iPriority; } - void SetPriority(int iPriority) { m_iPriority = iPriority; } - bool GetForcePriority() { return m_iPriority >= FORCE_PRIORITY; } - time_t GetMinTime() { return m_tMinTime; } - void SetMinTime(time_t tMinTime) { m_tMinTime = tMinTime; } - time_t GetMaxTime() { return m_tMaxTime; } - void SetMaxTime(time_t tMaxTime) { m_tMaxTime = tMaxTime; } + EKind GetKind() { return m_kind; } + void SetKind(EKind kind) { m_kind = kind; } + const char* GetURL() { return m_url; } // needs locking (for shared objects) + void SetURL(const char* url); // needs locking (for shared objects) + const char* GetFilename() { return m_filename; } + void SetFilename(const char* filename); + static void MakeNiceNZBName(const char* nzbFilename, char* buffer, int size, bool removeExt); + static void MakeNiceUrlName(const char* url, const char* nzbFilename, char* buffer, int size); + const char* GetDestDir() { return m_destDir; } // needs locking (for shared objects) + void SetDestDir(const char* destDir); // needs locking (for shared objects) + const char* GetFinalDir() { return m_finalDir; } // needs locking (for shared objects) + void SetFinalDir(const char* finalDir); // needs locking (for shared objects) + const char* GetCategory() { return m_category; } // needs locking (for shared objects) + void SetCategory(const char* category); // needs locking (for shared objects) + const char* GetName() { return m_name; } // needs locking (for shared objects) + void SetName(const char* name); // needs locking (for shared objects) + int GetFileCount() { return m_fileCount; } + void SetFileCount(int fileCount) { m_fileCount = fileCount; } + int GetParkedFileCount() { return m_parkedFileCount; } + void SetParkedFileCount(int parkedFileCount) { m_parkedFileCount = parkedFileCount; } + long long GetSize() { return m_size; } + void SetSize(long long size) { m_size = size; } + long long GetRemainingSize() { return m_remainingSize; } + void SetRemainingSize(long long remainingSize) { m_remainingSize = remainingSize; } + long long GetPausedSize() { return m_pausedSize; } + void SetPausedSize(long long pausedSize) { m_pausedSize = pausedSize; } + int GetPausedFileCount() { return m_pausedFileCount; } + void SetPausedFileCount(int pausedFileCount) { m_pausedFileCount = pausedFileCount; } + int GetRemainingParCount() { return m_remainingParCount; } + void SetRemainingParCount(int remainingParCount) { m_remainingParCount = remainingParCount; } + int GetActiveDownloads() { return m_activeDownloads; } + void SetActiveDownloads(int activeDownloads); + long long GetSuccessSize() { return m_successSize; } + void SetSuccessSize(long long successSize) { m_successSize = successSize; } + long long GetFailedSize() { return m_failedSize; } + void SetFailedSize(long long failedSize) { m_failedSize = failedSize; } + long long GetCurrentSuccessSize() { return m_currentSuccessSize; } + void SetCurrentSuccessSize(long long currentSuccessSize) { m_currentSuccessSize = currentSuccessSize; } + long long GetCurrentFailedSize() { return m_currentFailedSize; } + void SetCurrentFailedSize(long long currentFailedSize) { m_currentFailedSize = currentFailedSize; } + long long GetParSize() { return m_parSize; } + void SetParSize(long long parSize) { m_parSize = parSize; } + long long GetParSuccessSize() { return m_parSuccessSize; } + void SetParSuccessSize(long long parSuccessSize) { m_parSuccessSize = parSuccessSize; } + long long GetParFailedSize() { return m_parFailedSize; } + void SetParFailedSize(long long parFailedSize) { m_parFailedSize = parFailedSize; } + long long GetParCurrentSuccessSize() { return m_parCurrentSuccessSize; } + void SetParCurrentSuccessSize(long long parCurrentSuccessSize) { m_parCurrentSuccessSize = parCurrentSuccessSize; } + long long GetParCurrentFailedSize() { return m_parCurrentFailedSize; } + void SetParCurrentFailedSize(long long parCurrentFailedSize) { m_parCurrentFailedSize = parCurrentFailedSize; } + int GetTotalArticles() { return m_totalArticles; } + void SetTotalArticles(int totalArticles) { m_totalArticles = totalArticles; } + int GetSuccessArticles() { return m_successArticles; } + void SetSuccessArticles(int successArticles) { m_successArticles = successArticles; } + int GetFailedArticles() { return m_failedArticles; } + void SetFailedArticles(int failedArticles) { m_failedArticles = failedArticles; } + int GetCurrentSuccessArticles() { return m_currentSuccessArticles; } + void SetCurrentSuccessArticles(int currentSuccessArticles) { m_currentSuccessArticles = currentSuccessArticles; } + int GetCurrentFailedArticles() { return m_currentFailedArticles; } + void SetCurrentFailedArticles(int currentFailedArticles) { m_currentFailedArticles = currentFailedArticles; } + int GetPriority() { return m_priority; } + void SetPriority(int priority) { m_priority = priority; } + bool GetForcePriority() { return m_priority >= FORCE_PRIORITY; } + time_t GetMinTime() { return m_minTime; } + void SetMinTime(time_t minTime) { m_minTime = minTime; } + time_t GetMaxTime() { return m_maxTime; } + void SetMaxTime(time_t maxTime) { m_maxTime = maxTime; } void BuildDestDirName(); - void BuildFinalDirName(char* szFinalDirBuf, int iBufSize); + void BuildFinalDirName(char* finalDirBuf, int bufSize); CompletedFiles* GetCompletedFiles() { return &m_completedFiles; } // needs locking (for shared objects) void ClearCompletedFiles(); - ERenameStatus GetRenameStatus() { return m_eRenameStatus; } - void SetRenameStatus(ERenameStatus eRenameStatus) { m_eRenameStatus = eRenameStatus; } - EParStatus GetParStatus() { return m_eParStatus; } - void SetParStatus(EParStatus eParStatus) { m_eParStatus = eParStatus; } - EUnpackStatus GetUnpackStatus() { return m_eUnpackStatus; } - void SetUnpackStatus(EUnpackStatus eUnpackStatus) { m_eUnpackStatus = eUnpackStatus; } - ECleanupStatus GetCleanupStatus() { return m_eCleanupStatus; } - void SetCleanupStatus(ECleanupStatus eCleanupStatus) { m_eCleanupStatus = eCleanupStatus; } - EMoveStatus GetMoveStatus() { return m_eMoveStatus; } - void SetMoveStatus(EMoveStatus eMoveStatus) { m_eMoveStatus = eMoveStatus; } - EDeleteStatus GetDeleteStatus() { return m_eDeleteStatus; } - void SetDeleteStatus(EDeleteStatus eDeleteStatus) { m_eDeleteStatus = eDeleteStatus; } - EMarkStatus GetMarkStatus() { return m_eMarkStatus; } - void SetMarkStatus(EMarkStatus eMarkStatus) { m_eMarkStatus = eMarkStatus; } - EUrlStatus GetUrlStatus() { return m_eUrlStatus; } - int GetExtraParBlocks() { return m_iExtraParBlocks; } - void SetExtraParBlocks(int iExtraParBlocks) { m_iExtraParBlocks = iExtraParBlocks; } - void SetUrlStatus(EUrlStatus eUrlStatus) { m_eUrlStatus = eUrlStatus; } - const char* GetQueuedFilename() { return m_szQueuedFilename; } - void SetQueuedFilename(const char* szQueuedFilename); - bool GetDeleting() { return m_bDeleting; } - void SetDeleting(bool bDeleting) { m_bDeleting = bDeleting; } - bool GetDeletePaused() { return m_bDeletePaused; } - void SetDeletePaused(bool bDeletePaused) { m_bDeletePaused = bDeletePaused; } - bool GetManyDupeFiles() { return m_bManyDupeFiles; } - void SetManyDupeFiles(bool bManyDupeFiles) { m_bManyDupeFiles = bManyDupeFiles; } - bool GetAvoidHistory() { return m_bAvoidHistory; } - void SetAvoidHistory(bool bAvoidHistory) { m_bAvoidHistory = bAvoidHistory; } - bool GetHealthPaused() { return m_bHealthPaused; } - void SetHealthPaused(bool bHealthPaused) { m_bHealthPaused = bHealthPaused; } - bool GetParCleanup() { return m_bParCleanup; } - void SetParCleanup(bool bParCleanup) { m_bParCleanup = bParCleanup; } - bool GetCleanupDisk() { return m_bCleanupDisk; } - void SetCleanupDisk(bool bCleanupDisk) { m_bCleanupDisk = bCleanupDisk; } - bool GetUnpackCleanedUpDisk() { return m_bUnpackCleanedUpDisk; } - void SetUnpackCleanedUpDisk(bool bUnpackCleanedUpDisk) { m_bUnpackCleanedUpDisk = bUnpackCleanedUpDisk; } - bool GetAddUrlPaused() { return m_bAddUrlPaused; } - void SetAddUrlPaused(bool bAddUrlPaused) { m_bAddUrlPaused = bAddUrlPaused; } - FileList* GetFileList() { return &m_FileList; } // needs locking (for shared objects) + ERenameStatus GetRenameStatus() { return m_renameStatus; } + void SetRenameStatus(ERenameStatus renameStatus) { m_renameStatus = renameStatus; } + EParStatus GetParStatus() { return m_parStatus; } + void SetParStatus(EParStatus parStatus) { m_parStatus = parStatus; } + EUnpackStatus GetUnpackStatus() { return m_unpackStatus; } + void SetUnpackStatus(EUnpackStatus unpackStatus) { m_unpackStatus = unpackStatus; } + ECleanupStatus GetCleanupStatus() { return m_cleanupStatus; } + void SetCleanupStatus(ECleanupStatus cleanupStatus) { m_cleanupStatus = cleanupStatus; } + EMoveStatus GetMoveStatus() { return m_moveStatus; } + void SetMoveStatus(EMoveStatus moveStatus) { m_moveStatus = moveStatus; } + EDeleteStatus GetDeleteStatus() { return m_deleteStatus; } + void SetDeleteStatus(EDeleteStatus deleteStatus) { m_deleteStatus = deleteStatus; } + EMarkStatus GetMarkStatus() { return m_markStatus; } + void SetMarkStatus(EMarkStatus markStatus) { m_markStatus = markStatus; } + EUrlStatus GetUrlStatus() { return m_urlStatus; } + int GetExtraParBlocks() { return m_extraParBlocks; } + void SetExtraParBlocks(int extraParBlocks) { m_extraParBlocks = extraParBlocks; } + void SetUrlStatus(EUrlStatus urlStatus) { m_urlStatus = urlStatus; } + const char* GetQueuedFilename() { return m_queuedFilename; } + void SetQueuedFilename(const char* queuedFilename); + bool GetDeleting() { return m_deleting; } + void SetDeleting(bool deleting) { m_deleting = deleting; } + bool GetDeletePaused() { return m_deletePaused; } + void SetDeletePaused(bool deletePaused) { m_deletePaused = deletePaused; } + bool GetManyDupeFiles() { return m_manyDupeFiles; } + void SetManyDupeFiles(bool manyDupeFiles) { m_manyDupeFiles = manyDupeFiles; } + bool GetAvoidHistory() { return m_avoidHistory; } + void SetAvoidHistory(bool avoidHistory) { m_avoidHistory = avoidHistory; } + bool GetHealthPaused() { return m_healthPaused; } + void SetHealthPaused(bool healthPaused) { m_healthPaused = healthPaused; } + bool GetParCleanup() { return m_parCleanup; } + void SetParCleanup(bool parCleanup) { m_parCleanup = parCleanup; } + bool GetCleanupDisk() { return m_cleanupDisk; } + void SetCleanupDisk(bool cleanupDisk) { m_cleanupDisk = cleanupDisk; } + bool GetUnpackCleanedUpDisk() { return m_unpackCleanedUpDisk; } + void SetUnpackCleanedUpDisk(bool unpackCleanedUpDisk) { m_unpackCleanedUpDisk = unpackCleanedUpDisk; } + bool GetAddUrlPaused() { return m_addUrlPaused; } + void SetAddUrlPaused(bool addUrlPaused) { m_addUrlPaused = addUrlPaused; } + FileList* GetFileList() { return &m_fileList; } // needs locking (for shared objects) NZBParameterList* GetParameters() { return &m_ppParameters; } // needs locking (for shared objects) ScriptStatusList* GetScriptStatuses() { return &m_scriptStatuses; } // needs locking (for shared objects) - ServerStatList* GetServerStats() { return &m_ServerStats; } - ServerStatList* GetCurrentServerStats() { return &m_CurrentServerStats; } + ServerStatList* GetServerStats() { return &m_serverStats; } + ServerStatList* GetCurrentServerStats() { return &m_currentServerStats; } int CalcHealth(); - int CalcCriticalHealth(bool bAllowEstimation); - const char* GetDupeKey() { return m_szDupeKey; } // needs locking (for shared objects) - void SetDupeKey(const char* szDupeKey); // needs locking (for shared objects) - int GetDupeScore() { return m_iDupeScore; } - void SetDupeScore(int iDupeScore) { m_iDupeScore = iDupeScore; } - EDupeMode GetDupeMode() { return m_eDupeMode; } - void SetDupeMode(EDupeMode eDupeMode) { m_eDupeMode = eDupeMode; } - unsigned int GetFullContentHash() { return m_iFullContentHash; } - void SetFullContentHash(unsigned int iFullContentHash) { m_iFullContentHash = iFullContentHash; } - unsigned int GetFilteredContentHash() { return m_iFilteredContentHash; } - void SetFilteredContentHash(unsigned int iFilteredContentHash) { m_iFilteredContentHash = iFilteredContentHash; } - long long GetDownloadedSize() { return m_lDownloadedSize; } - void SetDownloadedSize(long long lDownloadedSize) { m_lDownloadedSize = lDownloadedSize; } - int GetDownloadSec() { return m_iDownloadSec; } - void SetDownloadSec(int iDownloadSec) { m_iDownloadSec = iDownloadSec; } - int GetPostTotalSec() { return m_iPostTotalSec; } - void SetPostTotalSec(int iPostTotalSec) { m_iPostTotalSec = iPostTotalSec; } - int GetParSec() { return m_iParSec; } - void SetParSec(int iParSec) { m_iParSec = iParSec; } - int GetRepairSec() { return m_iRepairSec; } - void SetRepairSec(int iRepairSec) { m_iRepairSec = iRepairSec; } - int GetUnpackSec() { return m_iUnpackSec; } - void SetUnpackSec(int iUnpackSec) { m_iUnpackSec = iUnpackSec; } - time_t GetDownloadStartTime() { return m_tDownloadStartTime; } - void SetDownloadStartTime(time_t tDownloadStartTime) { m_tDownloadStartTime = tDownloadStartTime; } - void SetReprocess(bool bReprocess) { m_bReprocess = bReprocess; } - bool GetReprocess() { return m_bReprocess; } - time_t GetQueueScriptTime() { return m_tQueueScriptTime; } - void SetQueueScriptTime(time_t tQueueScriptTime) { m_tQueueScriptTime = tQueueScriptTime; } - void SetParFull(bool bParFull) { m_bParFull = bParFull; } - bool GetParFull() { return m_bParFull; } - int GetFeedID() { return m_iFeedID; } - void SetFeedID(int iFeedID) { m_iFeedID = iFeedID; } + int CalcCriticalHealth(bool allowEstimation); + const char* GetDupeKey() { return m_dupeKey; } // needs locking (for shared objects) + void SetDupeKey(const char* dupeKey); // needs locking (for shared objects) + int GetDupeScore() { return m_dupeScore; } + void SetDupeScore(int dupeScore) { m_dupeScore = dupeScore; } + EDupeMode GetDupeMode() { return m_dupeMode; } + void SetDupeMode(EDupeMode dupeMode) { m_dupeMode = dupeMode; } + unsigned int GetFullContentHash() { return m_fullContentHash; } + void SetFullContentHash(unsigned int fullContentHash) { m_fullContentHash = fullContentHash; } + unsigned int GetFilteredContentHash() { return m_filteredContentHash; } + void SetFilteredContentHash(unsigned int filteredContentHash) { m_filteredContentHash = filteredContentHash; } + long long GetDownloadedSize() { return m_downloadedSize; } + void SetDownloadedSize(long long downloadedSize) { m_downloadedSize = downloadedSize; } + int GetDownloadSec() { return m_downloadSec; } + void SetDownloadSec(int downloadSec) { m_downloadSec = downloadSec; } + int GetPostTotalSec() { return m_postTotalSec; } + void SetPostTotalSec(int postTotalSec) { m_postTotalSec = postTotalSec; } + int GetParSec() { return m_parSec; } + void SetParSec(int parSec) { m_parSec = parSec; } + int GetRepairSec() { return m_repairSec; } + void SetRepairSec(int repairSec) { m_repairSec = repairSec; } + int GetUnpackSec() { return m_unpackSec; } + void SetUnpackSec(int unpackSec) { m_unpackSec = unpackSec; } + time_t GetDownloadStartTime() { return m_downloadStartTime; } + void SetDownloadStartTime(time_t downloadStartTime) { m_downloadStartTime = downloadStartTime; } + void SetReprocess(bool reprocess) { m_reprocess = reprocess; } + bool GetReprocess() { return m_reprocess; } + time_t GetQueueScriptTime() { return m_queueScriptTime; } + void SetQueueScriptTime(time_t queueScriptTime) { m_queueScriptTime = queueScriptTime; } + void SetParFull(bool parFull) { m_parFull = parFull; } + bool GetParFull() { return m_parFull; } + int GetFeedID() { return m_feedId; } + void SetFeedID(int feedId) { m_feedId = feedId; } - void CopyFileList(NZBInfo* pSrcNZBInfo); + void CopyFileList(NZBInfo* srcNzbInfo); void UpdateMinMaxTime(); - PostInfo* GetPostInfo() { return m_pPostInfo; } + PostInfo* GetPostInfo() { return m_postInfo; } void EnterPostProcess(); void LeavePostProcess(); bool IsDupeSuccess(); - const char* MakeTextStatus(bool bIgnoreScriptStatus); + const char* MakeTextStatus(bool ignoreScriptStatus); - void AddMessage(Message::EKind eKind, const char* szText); - void PrintMessage(Message::EKind eKind, const char* szFormat, ...); - int GetMessageCount() { return m_iMessageCount; } - void SetMessageCount(int iMessageCount) { m_iMessageCount = iMessageCount; } - int GetCachedMessageCount() { return m_iCachedMessageCount; } + void AddMessage(Message::EKind kind, const char* text); + void PrintMessage(Message::EKind kind, const char* format, ...); + int GetMessageCount() { return m_messageCount; } + void SetMessageCount(int messageCount) { m_messageCount = messageCount; } + int GetCachedMessageCount() { return m_cachedMessageCount; } MessageList* LockCachedMessages(); void UnlockCachedMessages(); }; @@ -692,14 +692,14 @@ typedef std::deque NZBQueueBase; class NZBList : public NZBQueueBase { private: - bool m_bOwnObjects; + bool m_ownObjects; public: - NZBList(bool bOwnObjects = false) { m_bOwnObjects = bOwnObjects; } + NZBList(bool ownObjects = false) { m_ownObjects = ownObjects; } ~NZBList(); void Clear(); - void Add(NZBInfo* pNZBInfo, bool bAddTop); - void Remove(NZBInfo* pNZBInfo); - NZBInfo* Find(int iID); + void Add(NZBInfo* nzbInfo, bool addTop); + void Remove(NZBInfo* nzbInfo); + NZBInfo* Find(int id); }; class PostInfo @@ -722,64 +722,64 @@ public: typedef std::vector ParredFiles; private: - NZBInfo* m_pNZBInfo; - bool m_bWorking; - bool m_bDeleted; - bool m_bRequestParCheck; - bool m_bForceParFull; - bool m_bForceRepair; - bool m_bParRepaired; - bool m_bUnpackTried; - bool m_bPassListTried; - int m_eLastUnpackStatus; - EStage m_eStage; - char* m_szProgressLabel; - int m_iFileProgress; - int m_iStageProgress; - time_t m_tStartTime; - time_t m_tStageTime; - Thread* m_pPostThread; + NZBInfo* m_nzbInfo; + bool m_working; + bool m_deleted; + bool m_requestParCheck; + bool m_forceParFull; + bool m_forceRepair; + bool m_parRepaired; + bool m_unpackTried; + bool m_passListTried; + int m_lastUnpackStatus; + EStage m_stage; + char* m_progressLabel; + int m_fileProgress; + int m_stageProgress; + time_t m_startTime; + time_t m_stageTime; + Thread* m_postThread; - ParredFiles m_ParredFiles; + ParredFiles m_parredFiles; public: PostInfo(); ~PostInfo(); - NZBInfo* GetNZBInfo() { return m_pNZBInfo; } - void SetNZBInfo(NZBInfo* pNZBInfo) { m_pNZBInfo = pNZBInfo; } - EStage GetStage() { return m_eStage; } - void SetStage(EStage eStage) { m_eStage = eStage; } - void SetProgressLabel(const char* szProgressLabel); - const char* GetProgressLabel() { return m_szProgressLabel; } - int GetFileProgress() { return m_iFileProgress; } - void SetFileProgress(int iFileProgress) { m_iFileProgress = iFileProgress; } - int GetStageProgress() { return m_iStageProgress; } - void SetStageProgress(int iStageProgress) { m_iStageProgress = iStageProgress; } - time_t GetStartTime() { return m_tStartTime; } - void SetStartTime(time_t tStartTime) { m_tStartTime = tStartTime; } - time_t GetStageTime() { return m_tStageTime; } - void SetStageTime(time_t tStageTime) { m_tStageTime = tStageTime; } - bool GetWorking() { return m_bWorking; } - void SetWorking(bool bWorking) { m_bWorking = bWorking; } - bool GetDeleted() { return m_bDeleted; } - void SetDeleted(bool bDeleted) { m_bDeleted = bDeleted; } - bool GetRequestParCheck() { return m_bRequestParCheck; } - void SetRequestParCheck(bool bRequestParCheck) { m_bRequestParCheck = bRequestParCheck; } - bool GetForceParFull() { return m_bForceParFull; } - void SetForceParFull(bool bForceParFull) { m_bForceParFull = bForceParFull; } - bool GetForceRepair() { return m_bForceRepair; } - void SetForceRepair(bool bForceRepair) { m_bForceRepair = bForceRepair; } - bool GetParRepaired() { return m_bParRepaired; } - void SetParRepaired(bool bParRepaired) { m_bParRepaired = bParRepaired; } - bool GetUnpackTried() { return m_bUnpackTried; } - void SetUnpackTried(bool bUnpackTried) { m_bUnpackTried = bUnpackTried; } - bool GetPassListTried() { return m_bPassListTried; } - void SetPassListTried(bool bPassListTried) { m_bPassListTried = bPassListTried; } - int GetLastUnpackStatus() { return m_eLastUnpackStatus; } - void SetLastUnpackStatus(int eUnpackStatus) { m_eLastUnpackStatus = eUnpackStatus; } - Thread* GetPostThread() { return m_pPostThread; } - void SetPostThread(Thread* pPostThread) { m_pPostThread = pPostThread; } - ParredFiles* GetParredFiles() { return &m_ParredFiles; } + NZBInfo* GetNZBInfo() { return m_nzbInfo; } + void SetNZBInfo(NZBInfo* nzbInfo) { m_nzbInfo = nzbInfo; } + EStage GetStage() { return m_stage; } + void SetStage(EStage stage) { m_stage = stage; } + void SetProgressLabel(const char* progressLabel); + const char* GetProgressLabel() { return m_progressLabel; } + int GetFileProgress() { return m_fileProgress; } + void SetFileProgress(int fileProgress) { m_fileProgress = fileProgress; } + int GetStageProgress() { return m_stageProgress; } + void SetStageProgress(int stageProgress) { m_stageProgress = stageProgress; } + time_t GetStartTime() { return m_startTime; } + void SetStartTime(time_t startTime) { m_startTime = startTime; } + time_t GetStageTime() { return m_stageTime; } + void SetStageTime(time_t stageTime) { m_stageTime = stageTime; } + bool GetWorking() { return m_working; } + void SetWorking(bool working) { m_working = working; } + bool GetDeleted() { return m_deleted; } + void SetDeleted(bool deleted) { m_deleted = deleted; } + bool GetRequestParCheck() { return m_requestParCheck; } + void SetRequestParCheck(bool requestParCheck) { m_requestParCheck = requestParCheck; } + bool GetForceParFull() { return m_forceParFull; } + void SetForceParFull(bool forceParFull) { m_forceParFull = forceParFull; } + bool GetForceRepair() { return m_forceRepair; } + void SetForceRepair(bool forceRepair) { m_forceRepair = forceRepair; } + bool GetParRepaired() { return m_parRepaired; } + void SetParRepaired(bool parRepaired) { m_parRepaired = parRepaired; } + bool GetUnpackTried() { return m_unpackTried; } + void SetUnpackTried(bool unpackTried) { m_unpackTried = unpackTried; } + bool GetPassListTried() { return m_passListTried; } + void SetPassListTried(bool passListTried) { m_passListTried = passListTried; } + int GetLastUnpackStatus() { return m_lastUnpackStatus; } + void SetLastUnpackStatus(int unpackStatus) { m_lastUnpackStatus = unpackStatus; } + Thread* GetPostThread() { return m_postThread; } + void SetPostThread(Thread* postThread) { m_postThread = postThread; } + ParredFiles* GetParredFiles() { return &m_parredFiles; } }; typedef std::vector IDList; @@ -801,37 +801,37 @@ public: }; private: - int m_iID; - char* m_szName; - char* m_szDupeKey; - int m_iDupeScore; - EDupeMode m_eDupeMode; - long long m_lSize; - unsigned int m_iFullContentHash; - unsigned int m_iFilteredContentHash; - EStatus m_eStatus; + int m_id; + char* m_name; + char* m_dupeKey; + int m_dupeScore; + EDupeMode m_dupeMode; + long long m_size; + unsigned int m_fullContentHash; + unsigned int m_filteredContentHash; + EStatus m_status; public: DupInfo(); ~DupInfo(); - int GetID() { return m_iID; } - void SetID(int iID); - const char* GetName() { return m_szName; } // needs locking (for shared objects) - void SetName(const char* szName); // needs locking (for shared objects) - const char* GetDupeKey() { return m_szDupeKey; } // needs locking (for shared objects) - void SetDupeKey(const char* szDupeKey); // needs locking (for shared objects) - int GetDupeScore() { return m_iDupeScore; } - void SetDupeScore(int iDupeScore) { m_iDupeScore = iDupeScore; } - EDupeMode GetDupeMode() { return m_eDupeMode; } - void SetDupeMode(EDupeMode eDupeMode) { m_eDupeMode = eDupeMode; } - long long GetSize() { return m_lSize; } - void SetSize(long long lSize) { m_lSize = lSize; } - unsigned int GetFullContentHash() { return m_iFullContentHash; } - void SetFullContentHash(unsigned int iFullContentHash) { m_iFullContentHash = iFullContentHash; } - unsigned int GetFilteredContentHash() { return m_iFilteredContentHash; } - void SetFilteredContentHash(unsigned int iFilteredContentHash) { m_iFilteredContentHash = iFilteredContentHash; } - EStatus GetStatus() { return m_eStatus; } - void SetStatus(EStatus Status) { m_eStatus = Status; } + int GetID() { return m_id; } + void SetID(int id); + const char* GetName() { return m_name; } // needs locking (for shared objects) + void SetName(const char* name); // needs locking (for shared objects) + const char* GetDupeKey() { return m_dupeKey; } // needs locking (for shared objects) + void SetDupeKey(const char* dupeKey); // needs locking (for shared objects) + int GetDupeScore() { return m_dupeScore; } + void SetDupeScore(int dupeScore) { m_dupeScore = dupeScore; } + EDupeMode GetDupeMode() { return m_dupeMode; } + void SetDupeMode(EDupeMode dupeMode) { m_dupeMode = dupeMode; } + long long GetSize() { return m_size; } + void SetSize(long long size) { m_size = size; } + unsigned int GetFullContentHash() { return m_fullContentHash; } + void SetFullContentHash(unsigned int fullContentHash) { m_fullContentHash = fullContentHash; } + unsigned int GetFilteredContentHash() { return m_filteredContentHash; } + void SetFilteredContentHash(unsigned int filteredContentHash) { m_filteredContentHash = filteredContentHash; } + EStatus GetStatus() { return m_status; } + void SetStatus(EStatus Status) { m_status = Status; } }; class HistoryInfo @@ -846,22 +846,22 @@ public: }; private: - EKind m_eKind; - void* m_pInfo; - time_t m_tTime; + EKind m_kind; + void* m_info; + time_t m_time; public: - HistoryInfo(NZBInfo* pNZBInfo); - HistoryInfo(DupInfo* pDupInfo); + HistoryInfo(NZBInfo* nzbInfo); + HistoryInfo(DupInfo* dupInfo); ~HistoryInfo(); - EKind GetKind() { return m_eKind; } + EKind GetKind() { return m_kind; } int GetID(); - NZBInfo* GetNZBInfo() { return (NZBInfo*)m_pInfo; } - DupInfo* GetDupInfo() { return (DupInfo*)m_pInfo; } - void DiscardNZBInfo() { m_pInfo = NULL; } - time_t GetTime() { return m_tTime; } - void SetTime(time_t tTime) { m_tTime = tTime; } - void GetName(char* szBuffer, int iSize); // needs locking (for shared objects) + NZBInfo* GetNZBInfo() { return (NZBInfo*)m_info; } + DupInfo* GetDupInfo() { return (DupInfo*)m_info; } + void DiscardNZBInfo() { m_info = NULL; } + time_t GetTime() { return m_time; } + void SetTime(time_t time) { m_time = time; } + void GetName(char* buffer, int size); // needs locking (for shared objects) }; typedef std::deque HistoryListBase; @@ -870,7 +870,7 @@ class HistoryList : public HistoryListBase { public: ~HistoryList(); - HistoryInfo* Find(int iID); + HistoryInfo* Find(int id); }; class DownloadQueue : public Subject @@ -888,10 +888,10 @@ public: struct Aspect { - EAspectAction eAction; - DownloadQueue* pDownloadQueue; - NZBInfo* pNZBInfo; - FileInfo* pFileInfo; + EAspectAction action; + DownloadQueue* downloadQueue; + NZBInfo* nzbInfo; + FileInfo* fileInfo; }; enum EEditAction @@ -952,16 +952,16 @@ public: }; private: - NZBList m_Queue; - HistoryList m_History; - Mutex m_LockMutex; + NZBList m_queue; + HistoryList m_history; + Mutex m_lockMutex; static DownloadQueue* g_pDownloadQueue; static bool g_bLoaded; protected: - DownloadQueue() : m_Queue(true) {} - static void Init(DownloadQueue* pGlobalInstance) { g_pDownloadQueue = pGlobalInstance; } + DownloadQueue() : m_queue(true) {} + static void Init(DownloadQueue* globalInstance) { g_pDownloadQueue = globalInstance; } static void Final() { g_pDownloadQueue = NULL; } static void Loaded() { g_bLoaded = true; } @@ -969,12 +969,12 @@ public: static bool IsLoaded() { return g_bLoaded; } static DownloadQueue* Lock(); static void Unlock(); - NZBList* GetQueue() { return &m_Queue; } - HistoryList* GetHistory() { return &m_History; } - virtual bool EditEntry(int ID, EEditAction eAction, int iOffset, const char* szText) = 0; - virtual bool EditList(IDList* pIDList, NameList* pNameList, EMatchMode eMatchMode, EEditAction eAction, int iOffset, const char* szText) = 0; + NZBList* GetQueue() { return &m_queue; } + HistoryList* GetHistory() { return &m_history; } + virtual bool EditEntry(int ID, EEditAction action, int offset, const char* text) = 0; + virtual bool EditList(IDList* idList, NameList* nameList, EMatchMode matchMode, EEditAction action, int offset, const char* text) = 0; virtual void Save() = 0; - void CalcRemainingSize(long long* pRemaining, long long* pRemainingForced); + void CalcRemainingSize(long long* remaining, long long* remainingForced); }; #endif diff --git a/daemon/queue/DupeCoordinator.cpp b/daemon/queue/DupeCoordinator.cpp index 42e249da..4ddf006e 100644 --- a/daemon/queue/DupeCoordinator.cpp +++ b/daemon/queue/DupeCoordinator.cpp @@ -50,12 +50,12 @@ #include "HistoryCoordinator.h" #include "DupeCoordinator.h" -bool DupeCoordinator::SameNameOrKey(const char* szName1, const char* szDupeKey1, - const char* szName2, const char* szDupeKey2) +bool DupeCoordinator::SameNameOrKey(const char* name1, const char* dupeKey1, + const char* name2, const char* dupeKey2) { - bool bHasDupeKeys = !Util::EmptyStr(szDupeKey1) && !Util::EmptyStr(szDupeKey2); - return (bHasDupeKeys && !strcmp(szDupeKey1, szDupeKey2)) || - (!bHasDupeKeys && !strcmp(szName1, szName2)); + bool hasDupeKeys = !Util::EmptyStr(dupeKey1) && !Util::EmptyStr(dupeKey2); + return (hasDupeKeys && !strcmp(dupeKey1, dupeKey2)) || + (!hasDupeKeys && !strcmp(name1, name2)); } /** @@ -72,46 +72,46 @@ bool DupeCoordinator::SameNameOrKey(const char* szName1, const char* szDupeKey1, the new item is added to queue; - if queue doesn't have duplicates - the new item is added to queue. */ -void DupeCoordinator::NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void DupeCoordinator::NZBFound(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { - debug("Checking duplicates for %s", pNZBInfo->GetName()); + debug("Checking duplicates for %s", nzbInfo->GetName()); // find duplicates in download queue with exactly same content - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pQueuedNZBInfo = *it; - bool bSameContent = (pNZBInfo->GetFullContentHash() > 0 && - pNZBInfo->GetFullContentHash() == pQueuedNZBInfo->GetFullContentHash()) || - (pNZBInfo->GetFilteredContentHash() > 0 && - pNZBInfo->GetFilteredContentHash() == pQueuedNZBInfo->GetFilteredContentHash()); + NZBInfo* queuedNzbInfo = *it; + bool sameContent = (nzbInfo->GetFullContentHash() > 0 && + nzbInfo->GetFullContentHash() == queuedNzbInfo->GetFullContentHash()) || + (nzbInfo->GetFilteredContentHash() > 0 && + nzbInfo->GetFilteredContentHash() == queuedNzbInfo->GetFilteredContentHash()); // if there is a duplicate with exactly same content (via hash-check) // in queue - the new item is skipped - if (pQueuedNZBInfo != pNZBInfo && bSameContent && pNZBInfo->GetKind() == NZBInfo::nkNzb) + if (queuedNzbInfo != nzbInfo && sameContent && nzbInfo->GetKind() == NZBInfo::nkNzb) { - char szMessage[1024]; - if (!strcmp(pNZBInfo->GetName(), pQueuedNZBInfo->GetName())) + char message[1024]; + if (!strcmp(nzbInfo->GetName(), queuedNzbInfo->GetName())) { - snprintf(szMessage, 1024, "Skipping duplicate %s, already queued", pNZBInfo->GetName()); + snprintf(message, 1024, "Skipping duplicate %s, already queued", nzbInfo->GetName()); } else { - snprintf(szMessage, 1024, "Skipping duplicate %s, already queued as %s", - pNZBInfo->GetName(), pQueuedNZBInfo->GetName()); + snprintf(message, 1024, "Skipping duplicate %s, already queued as %s", + nzbInfo->GetName(), queuedNzbInfo->GetName()); } - szMessage[1024-1] = '\0'; + message[1024-1] = '\0'; - if (pNZBInfo->GetFeedID()) + if (nzbInfo->GetFeedID()) { - warn("%s", szMessage); + warn("%s", message); // Flag saying QueueCoordinator to skip nzb-file - pNZBInfo->SetDeleteStatus(NZBInfo::dsManual); - g_pHistoryCoordinator->DeleteDiskFiles(pNZBInfo); + nzbInfo->SetDeleteStatus(NZBInfo::dsManual); + g_pHistoryCoordinator->DeleteDiskFiles(nzbInfo); } else { - pNZBInfo->SetDeleteStatus(NZBInfo::dsCopy); - pNZBInfo->AddMessage(Message::mkWarning, szMessage); + nzbInfo->SetDeleteStatus(NZBInfo::dsCopy); + nzbInfo->AddMessage(Message::mkWarning, message); } return; @@ -121,45 +121,45 @@ void DupeCoordinator::NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) // if download has empty dupekey and empty dupescore - check if download queue // or history have an item with the same name and non empty dupekey or dupescore and // take these properties from this item - if (Util::EmptyStr(pNZBInfo->GetDupeKey()) && pNZBInfo->GetDupeScore() == 0) + if (Util::EmptyStr(nzbInfo->GetDupeKey()) && nzbInfo->GetDupeScore() == 0) { - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pQueuedNZBInfo = *it; - if (!strcmp(pQueuedNZBInfo->GetName(), pNZBInfo->GetName()) && - (!Util::EmptyStr(pQueuedNZBInfo->GetDupeKey()) || pQueuedNZBInfo->GetDupeScore() != 0)) + NZBInfo* queuedNzbInfo = *it; + if (!strcmp(queuedNzbInfo->GetName(), nzbInfo->GetName()) && + (!Util::EmptyStr(queuedNzbInfo->GetDupeKey()) || queuedNzbInfo->GetDupeScore() != 0)) { - pNZBInfo->SetDupeKey(pQueuedNZBInfo->GetDupeKey()); - pNZBInfo->SetDupeScore(pQueuedNZBInfo->GetDupeScore()); + nzbInfo->SetDupeKey(queuedNzbInfo->GetDupeKey()); + nzbInfo->SetDupeScore(queuedNzbInfo->GetDupeScore()); info("Assigning dupekey %s and dupescore %i to %s from existing queue item with the same name", - pNZBInfo->GetDupeKey(), pNZBInfo->GetDupeScore(), pNZBInfo->GetName()); + nzbInfo->GetDupeKey(), nzbInfo->GetDupeScore(), nzbInfo->GetName()); break; } } } - if (Util::EmptyStr(pNZBInfo->GetDupeKey()) && pNZBInfo->GetDupeScore() == 0) + if (Util::EmptyStr(nzbInfo->GetDupeKey()) && nzbInfo->GetDupeScore() == 0) { - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - !strcmp(pHistoryInfo->GetNZBInfo()->GetName(), pNZBInfo->GetName()) && - (!Util::EmptyStr(pHistoryInfo->GetNZBInfo()->GetDupeKey()) || pHistoryInfo->GetNZBInfo()->GetDupeScore() != 0)) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + !strcmp(historyInfo->GetNZBInfo()->GetName(), nzbInfo->GetName()) && + (!Util::EmptyStr(historyInfo->GetNZBInfo()->GetDupeKey()) || historyInfo->GetNZBInfo()->GetDupeScore() != 0)) { - pNZBInfo->SetDupeKey(pHistoryInfo->GetNZBInfo()->GetDupeKey()); - pNZBInfo->SetDupeScore(pHistoryInfo->GetNZBInfo()->GetDupeScore()); + nzbInfo->SetDupeKey(historyInfo->GetNZBInfo()->GetDupeKey()); + nzbInfo->SetDupeScore(historyInfo->GetNZBInfo()->GetDupeScore()); info("Assigning dupekey %s and dupescore %i to %s from existing history item with the same name", - pNZBInfo->GetDupeKey(), pNZBInfo->GetDupeScore(), pNZBInfo->GetName()); + nzbInfo->GetDupeKey(), nzbInfo->GetDupeScore(), nzbInfo->GetName()); break; } - if (pHistoryInfo->GetKind() == HistoryInfo::hkDup && - !strcmp(pHistoryInfo->GetDupInfo()->GetName(), pNZBInfo->GetName()) && - (!Util::EmptyStr(pHistoryInfo->GetDupInfo()->GetDupeKey()) || pHistoryInfo->GetDupInfo()->GetDupeScore() != 0)) + if (historyInfo->GetKind() == HistoryInfo::hkDup && + !strcmp(historyInfo->GetDupInfo()->GetName(), nzbInfo->GetName()) && + (!Util::EmptyStr(historyInfo->GetDupInfo()->GetDupeKey()) || historyInfo->GetDupInfo()->GetDupeScore() != 0)) { - pNZBInfo->SetDupeKey(pHistoryInfo->GetDupInfo()->GetDupeKey()); - pNZBInfo->SetDupeScore(pHistoryInfo->GetDupInfo()->GetDupeScore()); + nzbInfo->SetDupeKey(historyInfo->GetDupInfo()->GetDupeKey()); + nzbInfo->SetDupeScore(historyInfo->GetDupInfo()->GetDupeScore()); info("Assigning dupekey %s and dupescore %i to %s from existing history item with the same name", - pNZBInfo->GetDupeKey(), pNZBInfo->GetDupeScore(), pNZBInfo->GetName()); + nzbInfo->GetDupeKey(), nzbInfo->GetDupeScore(), nzbInfo->GetName()); break; } } @@ -167,118 +167,118 @@ void DupeCoordinator::NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) // find duplicates in history - bool bSkip = false; - bool bGood = false; - bool bSameContent = false; - const char* szDupeName = NULL; + bool skip = false; + bool good = false; + bool sameContent = false; + const char* dupeName = NULL; // find duplicates in history having exactly same content // also: nzb-files having duplicates marked as good are skipped // also (only in score mode): nzb-files having success-duplicates in dup-history but not having duplicates in recent history are skipped - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; + HistoryInfo* historyInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - ((pNZBInfo->GetFullContentHash() > 0 && - pNZBInfo->GetFullContentHash() == pHistoryInfo->GetNZBInfo()->GetFullContentHash()) || - (pNZBInfo->GetFilteredContentHash() > 0 && - pNZBInfo->GetFilteredContentHash() == pHistoryInfo->GetNZBInfo()->GetFilteredContentHash()))) + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + ((nzbInfo->GetFullContentHash() > 0 && + nzbInfo->GetFullContentHash() == historyInfo->GetNZBInfo()->GetFullContentHash()) || + (nzbInfo->GetFilteredContentHash() > 0 && + nzbInfo->GetFilteredContentHash() == historyInfo->GetNZBInfo()->GetFilteredContentHash()))) { - bSkip = true; - bSameContent = true; - szDupeName = pHistoryInfo->GetNZBInfo()->GetName(); + skip = true; + sameContent = true; + dupeName = historyInfo->GetNZBInfo()->GetName(); break; } - if (pHistoryInfo->GetKind() == HistoryInfo::hkDup && - ((pNZBInfo->GetFullContentHash() > 0 && - pNZBInfo->GetFullContentHash() == pHistoryInfo->GetDupInfo()->GetFullContentHash()) || - (pNZBInfo->GetFilteredContentHash() > 0 && - pNZBInfo->GetFilteredContentHash() == pHistoryInfo->GetDupInfo()->GetFilteredContentHash()))) + if (historyInfo->GetKind() == HistoryInfo::hkDup && + ((nzbInfo->GetFullContentHash() > 0 && + nzbInfo->GetFullContentHash() == historyInfo->GetDupInfo()->GetFullContentHash()) || + (nzbInfo->GetFilteredContentHash() > 0 && + nzbInfo->GetFilteredContentHash() == historyInfo->GetDupInfo()->GetFilteredContentHash()))) { - bSkip = true; - bSameContent = true; - szDupeName = pHistoryInfo->GetDupInfo()->GetName(); + skip = true; + sameContent = true; + dupeName = historyInfo->GetDupInfo()->GetName(); break; } - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetDupeMode() != dmForce && - pHistoryInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksGood && - SameNameOrKey(pHistoryInfo->GetNZBInfo()->GetName(), pHistoryInfo->GetNZBInfo()->GetDupeKey(), - pNZBInfo->GetName(), pNZBInfo->GetDupeKey())) + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetDupeMode() != dmForce && + historyInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksGood && + SameNameOrKey(historyInfo->GetNZBInfo()->GetName(), historyInfo->GetNZBInfo()->GetDupeKey(), + nzbInfo->GetName(), nzbInfo->GetDupeKey())) { - bSkip = true; - bGood = true; - szDupeName = pHistoryInfo->GetNZBInfo()->GetName(); + skip = true; + good = true; + dupeName = historyInfo->GetNZBInfo()->GetName(); break; } - if (pHistoryInfo->GetKind() == HistoryInfo::hkDup && - pHistoryInfo->GetDupInfo()->GetDupeMode() != dmForce && - (pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood || - (pNZBInfo->GetDupeMode() == dmScore && - pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsSuccess && - pNZBInfo->GetDupeScore() <= pHistoryInfo->GetDupInfo()->GetDupeScore())) && - SameNameOrKey(pHistoryInfo->GetDupInfo()->GetName(), pHistoryInfo->GetDupInfo()->GetDupeKey(), - pNZBInfo->GetName(), pNZBInfo->GetDupeKey())) + if (historyInfo->GetKind() == HistoryInfo::hkDup && + historyInfo->GetDupInfo()->GetDupeMode() != dmForce && + (historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood || + (nzbInfo->GetDupeMode() == dmScore && + historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsSuccess && + nzbInfo->GetDupeScore() <= historyInfo->GetDupInfo()->GetDupeScore())) && + SameNameOrKey(historyInfo->GetDupInfo()->GetName(), historyInfo->GetDupInfo()->GetDupeKey(), + nzbInfo->GetName(), nzbInfo->GetDupeKey())) { - bSkip = true; - bGood = pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood; - szDupeName = pHistoryInfo->GetDupInfo()->GetName(); + skip = true; + good = historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood; + dupeName = historyInfo->GetDupInfo()->GetName(); break; } } - if (!bSameContent && !bGood && pNZBInfo->GetDupeMode() == dmScore) + if (!sameContent && !good && nzbInfo->GetDupeMode() == dmScore) { // nzb-files having success-duplicates in recent history (with different content) are added to history for backup - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetDupeMode() != dmForce && - SameNameOrKey(pHistoryInfo->GetNZBInfo()->GetName(), pHistoryInfo->GetNZBInfo()->GetDupeKey(), - pNZBInfo->GetName(), pNZBInfo->GetDupeKey()) && - pNZBInfo->GetDupeScore() <= pHistoryInfo->GetNZBInfo()->GetDupeScore() && - pHistoryInfo->GetNZBInfo()->IsDupeSuccess()) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetDupeMode() != dmForce && + SameNameOrKey(historyInfo->GetNZBInfo()->GetName(), historyInfo->GetNZBInfo()->GetDupeKey(), + nzbInfo->GetName(), nzbInfo->GetDupeKey()) && + nzbInfo->GetDupeScore() <= historyInfo->GetNZBInfo()->GetDupeScore() && + historyInfo->GetNZBInfo()->IsDupeSuccess()) { // Flag saying QueueCoordinator to skip nzb-file - pNZBInfo->SetDeleteStatus(NZBInfo::dsDupe); - info("Collection %s is a duplicate to %s", pNZBInfo->GetName(), pHistoryInfo->GetNZBInfo()->GetName()); + nzbInfo->SetDeleteStatus(NZBInfo::dsDupe); + info("Collection %s is a duplicate to %s", nzbInfo->GetName(), historyInfo->GetNZBInfo()->GetName()); return; } } } - if (bSkip) + if (skip) { - char szMessage[1024]; - if (!strcmp(pNZBInfo->GetName(), szDupeName)) + char message[1024]; + if (!strcmp(nzbInfo->GetName(), dupeName)) { - snprintf(szMessage, 1024, "Skipping duplicate %s, found in history with %s", pNZBInfo->GetName(), - bSameContent ? "exactly same content" : bGood ? "good status" : "success status"); + snprintf(message, 1024, "Skipping duplicate %s, found in history with %s", nzbInfo->GetName(), + sameContent ? "exactly same content" : good ? "good status" : "success status"); } else { - snprintf(szMessage, 1024, "Skipping duplicate %s, found in history %s with %s", - pNZBInfo->GetName(), szDupeName, - bSameContent ? "exactly same content" : bGood ? "good status" : "success status"); + snprintf(message, 1024, "Skipping duplicate %s, found in history %s with %s", + nzbInfo->GetName(), dupeName, + sameContent ? "exactly same content" : good ? "good status" : "success status"); } - szMessage[1024-1] = '\0'; + message[1024-1] = '\0'; - if (pNZBInfo->GetFeedID()) + if (nzbInfo->GetFeedID()) { - warn("%s", szMessage); + warn("%s", message); // Flag saying QueueCoordinator to skip nzb-file - pNZBInfo->SetDeleteStatus(NZBInfo::dsManual); - g_pHistoryCoordinator->DeleteDiskFiles(pNZBInfo); + nzbInfo->SetDeleteStatus(NZBInfo::dsManual); + g_pHistoryCoordinator->DeleteDiskFiles(nzbInfo); } else { - pNZBInfo->SetDeleteStatus(bSameContent ? NZBInfo::dsCopy : NZBInfo::dsGood); - pNZBInfo->AddMessage(Message::mkWarning, szMessage); + nzbInfo->SetDeleteStatus(sameContent ? NZBInfo::dsCopy : NZBInfo::dsGood); + nzbInfo->AddMessage(Message::mkWarning, message); } return; @@ -286,40 +286,40 @@ void DupeCoordinator::NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) // find duplicates in download queue and post-queue and handle both items according to their scores: // only one item remains in queue and another one is moved to history as dupe-backup - if (pNZBInfo->GetDupeMode() == dmScore) + if (nzbInfo->GetDupeMode() == dmScore) { // find duplicates in download queue int index = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); index++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); index++) { - NZBInfo* pQueuedNZBInfo = *it++; - if (pQueuedNZBInfo != pNZBInfo && - pQueuedNZBInfo->GetKind() == NZBInfo::nkNzb && - pQueuedNZBInfo->GetDupeMode() != dmForce && - SameNameOrKey(pQueuedNZBInfo->GetName(), pQueuedNZBInfo->GetDupeKey(), - pNZBInfo->GetName(), pNZBInfo->GetDupeKey())) + NZBInfo* queuedNzbInfo = *it++; + if (queuedNzbInfo != nzbInfo && + queuedNzbInfo->GetKind() == NZBInfo::nkNzb && + queuedNzbInfo->GetDupeMode() != dmForce && + SameNameOrKey(queuedNzbInfo->GetName(), queuedNzbInfo->GetDupeKey(), + nzbInfo->GetName(), nzbInfo->GetDupeKey())) { // if queue has a duplicate with the same or higher score - the new item // is moved to history as dupe-backup - if (pNZBInfo->GetDupeScore() <= pQueuedNZBInfo->GetDupeScore()) + if (nzbInfo->GetDupeScore() <= queuedNzbInfo->GetDupeScore()) { // Flag saying QueueCoordinator to skip nzb-file - pNZBInfo->SetDeleteStatus(NZBInfo::dsDupe); - info("Collection %s is a duplicate to %s", pNZBInfo->GetName(), pQueuedNZBInfo->GetName()); + nzbInfo->SetDeleteStatus(NZBInfo::dsDupe); + info("Collection %s is a duplicate to %s", nzbInfo->GetName(), queuedNzbInfo->GetName()); return; } // if queue has a duplicate with lower score - the existing item is moved // to history as dupe-backup (unless it is in post-processing stage) and // the new item is added to queue (unless it is in post-processing stage) - if (!pQueuedNZBInfo->GetPostInfo()) + if (!queuedNzbInfo->GetPostInfo()) { // the existing queue item is moved to history as dupe-backup - info("Moving collection %s with lower duplicate score to history", pQueuedNZBInfo->GetName()); - pQueuedNZBInfo->SetDeleteStatus(NZBInfo::dsDupe); - pDownloadQueue->EditEntry(pQueuedNZBInfo->GetID(), + info("Moving collection %s with lower duplicate score to history", queuedNzbInfo->GetName()); + queuedNzbInfo->SetDeleteStatus(NZBInfo::dsDupe); + downloadQueue->EditEntry(queuedNzbInfo->GetID(), DownloadQueue::eaGroupDelete, 0, NULL); - it = pDownloadQueue->GetQueue()->begin() + index; + it = downloadQueue->GetQueue()->begin() + index; } } } @@ -331,57 +331,57 @@ void DupeCoordinator::NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) return the best duplicate from history to queue for download; - if download of an item completes successfully - nothing extra needs to be done; */ -void DupeCoordinator::NZBCompleted(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void DupeCoordinator::NZBCompleted(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { - debug("Processing duplicates for %s", pNZBInfo->GetName()); + debug("Processing duplicates for %s", nzbInfo->GetName()); - if (pNZBInfo->GetDupeMode() == dmScore && !pNZBInfo->IsDupeSuccess()) + if (nzbInfo->GetDupeMode() == dmScore && !nzbInfo->IsDupeSuccess()) { - ReturnBestDupe(pDownloadQueue, pNZBInfo, pNZBInfo->GetName(), pNZBInfo->GetDupeKey()); + ReturnBestDupe(downloadQueue, nzbInfo, nzbInfo->GetName(), nzbInfo->GetDupeKey()); } } /** Returns the best duplicate from history to download queue. */ -void DupeCoordinator::ReturnBestDupe(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szNZBName, const char* szDupeKey) +void DupeCoordinator::ReturnBestDupe(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* nzbName, const char* dupeKey) { // check if history (recent or dup) has other success-duplicates or good-duplicates - bool bHistoryDupe = false; - int iHistoryScore = 0; - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + bool dupeFound = false; + int historyScore = 0; + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - bool bGoodDupe = false; + HistoryInfo* historyInfo = *it; + bool goodDupe = false; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetDupeMode() != dmForce && - pHistoryInfo->GetNZBInfo()->IsDupeSuccess() && - SameNameOrKey(pHistoryInfo->GetNZBInfo()->GetName(), pHistoryInfo->GetNZBInfo()->GetDupeKey(), szNZBName, szDupeKey)) + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetDupeMode() != dmForce && + historyInfo->GetNZBInfo()->IsDupeSuccess() && + SameNameOrKey(historyInfo->GetNZBInfo()->GetName(), historyInfo->GetNZBInfo()->GetDupeKey(), nzbName, dupeKey)) { - if (!bHistoryDupe || pHistoryInfo->GetNZBInfo()->GetDupeScore() > iHistoryScore) + if (!dupeFound || historyInfo->GetNZBInfo()->GetDupeScore() > historyScore) { - iHistoryScore = pHistoryInfo->GetNZBInfo()->GetDupeScore(); + historyScore = historyInfo->GetNZBInfo()->GetDupeScore(); } - bHistoryDupe = true; - bGoodDupe = pHistoryInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksGood; + dupeFound = true; + goodDupe = historyInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksGood; } - if (pHistoryInfo->GetKind() == HistoryInfo::hkDup && - pHistoryInfo->GetDupInfo()->GetDupeMode() != dmForce && - (pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsSuccess || - pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood) && - SameNameOrKey(pHistoryInfo->GetDupInfo()->GetName(), pHistoryInfo->GetDupInfo()->GetDupeKey(), szNZBName, szDupeKey)) + if (historyInfo->GetKind() == HistoryInfo::hkDup && + historyInfo->GetDupInfo()->GetDupeMode() != dmForce && + (historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsSuccess || + historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood) && + SameNameOrKey(historyInfo->GetDupInfo()->GetName(), historyInfo->GetDupInfo()->GetDupeKey(), nzbName, dupeKey)) { - if (!bHistoryDupe || pHistoryInfo->GetDupInfo()->GetDupeScore() > iHistoryScore) + if (!dupeFound || historyInfo->GetDupInfo()->GetDupeScore() > historyScore) { - iHistoryScore = pHistoryInfo->GetDupInfo()->GetDupeScore(); + historyScore = historyInfo->GetDupInfo()->GetDupeScore(); } - bHistoryDupe = true; - bGoodDupe = pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood; + dupeFound = true; + goodDupe = historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood; } - if (bGoodDupe) + if (goodDupe) { // another duplicate with good-status exists - exit without moving other dupes to queue return; @@ -389,128 +389,128 @@ void DupeCoordinator::ReturnBestDupe(DownloadQueue* pDownloadQueue, NZBInfo* pNZ } // check if duplicates exist in download queue - bool bQueueDupe = false; - int iQueueScore = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + bool queueDupe = false; + int queueScore = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pQueuedNZBInfo = *it; - if (pQueuedNZBInfo != pNZBInfo && - pQueuedNZBInfo->GetKind() == NZBInfo::nkNzb && - pQueuedNZBInfo->GetDupeMode() != dmForce && - SameNameOrKey(pQueuedNZBInfo->GetName(), pQueuedNZBInfo->GetDupeKey(), szNZBName, szDupeKey) && - (!bQueueDupe || pQueuedNZBInfo->GetDupeScore() > iQueueScore)) + NZBInfo* queuedNzbInfo = *it; + if (queuedNzbInfo != nzbInfo && + queuedNzbInfo->GetKind() == NZBInfo::nkNzb && + queuedNzbInfo->GetDupeMode() != dmForce && + SameNameOrKey(queuedNzbInfo->GetName(), queuedNzbInfo->GetDupeKey(), nzbName, dupeKey) && + (!queueDupe || queuedNzbInfo->GetDupeScore() > queueScore)) { - iQueueScore = pQueuedNZBInfo->GetDupeScore(); - bQueueDupe = true; + queueScore = queuedNzbInfo->GetDupeScore(); + queueDupe = true; } } // find dupe-backup with highest score, whose score is also higher than other // success-duplicates and higher than already queued items - HistoryInfo* pHistoryDupe = NULL; - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + HistoryInfo* historyDupe = NULL; + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetDupeMode() != dmForce && - pHistoryInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsDupe && - pHistoryInfo->GetNZBInfo()->CalcHealth() >= pHistoryInfo->GetNZBInfo()->CalcCriticalHealth(true) && - pHistoryInfo->GetNZBInfo()->GetMarkStatus() != NZBInfo::ksBad && - (!bHistoryDupe || pHistoryInfo->GetNZBInfo()->GetDupeScore() > iHistoryScore) && - (!bQueueDupe || pHistoryInfo->GetNZBInfo()->GetDupeScore() > iQueueScore) && - (!pHistoryDupe || pHistoryInfo->GetNZBInfo()->GetDupeScore() > pHistoryDupe->GetNZBInfo()->GetDupeScore()) && - SameNameOrKey(pHistoryInfo->GetNZBInfo()->GetName(), pHistoryInfo->GetNZBInfo()->GetDupeKey(), szNZBName, szDupeKey)) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetDupeMode() != dmForce && + historyInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsDupe && + historyInfo->GetNZBInfo()->CalcHealth() >= historyInfo->GetNZBInfo()->CalcCriticalHealth(true) && + historyInfo->GetNZBInfo()->GetMarkStatus() != NZBInfo::ksBad && + (!dupeFound || historyInfo->GetNZBInfo()->GetDupeScore() > historyScore) && + (!queueDupe || historyInfo->GetNZBInfo()->GetDupeScore() > queueScore) && + (!historyDupe || historyInfo->GetNZBInfo()->GetDupeScore() > historyDupe->GetNZBInfo()->GetDupeScore()) && + SameNameOrKey(historyInfo->GetNZBInfo()->GetName(), historyInfo->GetNZBInfo()->GetDupeKey(), nzbName, dupeKey)) { - pHistoryDupe = pHistoryInfo; + historyDupe = historyInfo; } } // move that dupe-backup from history to download queue - if (pHistoryDupe) + if (historyDupe) { - info("Found duplicate %s for %s", pHistoryDupe->GetNZBInfo()->GetName(), szNZBName); - g_pHistoryCoordinator->Redownload(pDownloadQueue, pHistoryDupe); + info("Found duplicate %s for %s", historyDupe->GetNZBInfo()->GetName(), nzbName); + g_pHistoryCoordinator->Redownload(downloadQueue, historyDupe); } } -void DupeCoordinator::HistoryMark(DownloadQueue* pDownloadQueue, HistoryInfo* pHistoryInfo, NZBInfo::EMarkStatus eMarkStatus) +void DupeCoordinator::HistoryMark(DownloadQueue* downloadQueue, HistoryInfo* historyInfo, NZBInfo::EMarkStatus markStatus) { - char szNZBName[1024]; - pHistoryInfo->GetName(szNZBName, 1024); + char nzbName[1024]; + historyInfo->GetName(nzbName, 1024); - const char* szMarkStatusName[] = { "NONE", "bad", "good", "success" }; + const char* markStatusName[] = { "NONE", "bad", "good", "success" }; - info("Marking %s as %s", szNZBName, szMarkStatusName[eMarkStatus]); + info("Marking %s as %s", nzbName, markStatusName[markStatus]); - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { - pHistoryInfo->GetNZBInfo()->SetMarkStatus(eMarkStatus); + historyInfo->GetNZBInfo()->SetMarkStatus(markStatus); } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkDup) + else if (historyInfo->GetKind() == HistoryInfo::hkDup) { - pHistoryInfo->GetDupInfo()->SetStatus( - eMarkStatus == NZBInfo::ksGood ? DupInfo::dsGood : - eMarkStatus == NZBInfo::ksSuccess ? DupInfo::dsSuccess : + historyInfo->GetDupInfo()->SetStatus( + markStatus == NZBInfo::ksGood ? DupInfo::dsGood : + markStatus == NZBInfo::ksSuccess ? DupInfo::dsSuccess : DupInfo::dsBad); } else { - error("Could not mark %s as bad: history item has wrong type", szNZBName); + error("Could not mark %s as bad: history item has wrong type", nzbName); return; } if (!g_pOptions->GetDupeCheck() || - (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetDupeMode() == dmForce) || - (pHistoryInfo->GetKind() == HistoryInfo::hkDup && - pHistoryInfo->GetDupInfo()->GetDupeMode() == dmForce)) + (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetDupeMode() == dmForce) || + (historyInfo->GetKind() == HistoryInfo::hkDup && + historyInfo->GetDupInfo()->GetDupeMode() == dmForce)) { return; } - if (eMarkStatus == NZBInfo::ksGood) + if (markStatus == NZBInfo::ksGood) { // mark as good // moving all duplicates from history to dup-history - HistoryCleanup(pDownloadQueue, pHistoryInfo); + HistoryCleanup(downloadQueue, historyInfo); } - else if (eMarkStatus == NZBInfo::ksBad) + else if (markStatus == NZBInfo::ksBad) { // mark as bad - const char* szDupeKey = pHistoryInfo->GetKind() == HistoryInfo::hkNzb ? pHistoryInfo->GetNZBInfo()->GetDupeKey() : - pHistoryInfo->GetKind() == HistoryInfo::hkDup ? pHistoryInfo->GetDupInfo()->GetDupeKey() : + const char* dupeKey = historyInfo->GetKind() == HistoryInfo::hkNzb ? historyInfo->GetNZBInfo()->GetDupeKey() : + historyInfo->GetKind() == HistoryInfo::hkDup ? historyInfo->GetDupInfo()->GetDupeKey() : NULL; - ReturnBestDupe(pDownloadQueue, NULL, szNZBName, szDupeKey); + ReturnBestDupe(downloadQueue, NULL, nzbName, dupeKey); } } -void DupeCoordinator::HistoryCleanup(DownloadQueue* pDownloadQueue, HistoryInfo* pMarkHistoryInfo) +void DupeCoordinator::HistoryCleanup(DownloadQueue* downloadQueue, HistoryInfo* markHistoryInfo) { - const char* szDupeKey = pMarkHistoryInfo->GetKind() == HistoryInfo::hkNzb ? pMarkHistoryInfo->GetNZBInfo()->GetDupeKey() : - pMarkHistoryInfo->GetKind() == HistoryInfo::hkDup ? pMarkHistoryInfo->GetDupInfo()->GetDupeKey() : + const char* dupeKey = markHistoryInfo->GetKind() == HistoryInfo::hkNzb ? markHistoryInfo->GetNZBInfo()->GetDupeKey() : + markHistoryInfo->GetKind() == HistoryInfo::hkDup ? markHistoryInfo->GetDupInfo()->GetDupeKey() : NULL; - const char* szNZBName = pMarkHistoryInfo->GetKind() == HistoryInfo::hkNzb ? pMarkHistoryInfo->GetNZBInfo()->GetName() : - pMarkHistoryInfo->GetKind() == HistoryInfo::hkDup ? pMarkHistoryInfo->GetDupInfo()->GetName() : + const char* nzbName = markHistoryInfo->GetKind() == HistoryInfo::hkNzb ? markHistoryInfo->GetNZBInfo()->GetName() : + markHistoryInfo->GetKind() == HistoryInfo::hkDup ? markHistoryInfo->GetDupInfo()->GetName() : NULL; - bool bChanged = false; + bool changed = false; int index = 0; // traversing in a reverse order to delete items in order they were added to history // (just to produce the log-messages in a more logical order) - for (HistoryList::reverse_iterator it = pDownloadQueue->GetHistory()->rbegin(); it != pDownloadQueue->GetHistory()->rend(); ) + for (HistoryList::reverse_iterator it = downloadQueue->GetHistory()->rbegin(); it != downloadQueue->GetHistory()->rend(); ) { - HistoryInfo* pHistoryInfo = *it; + HistoryInfo* historyInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetDupeMode() != dmForce && - pHistoryInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsDupe && - pHistoryInfo != pMarkHistoryInfo && - SameNameOrKey(pHistoryInfo->GetNZBInfo()->GetName(), pHistoryInfo->GetNZBInfo()->GetDupeKey(), szNZBName, szDupeKey)) + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetDupeMode() != dmForce && + historyInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsDupe && + historyInfo != markHistoryInfo && + SameNameOrKey(historyInfo->GetNZBInfo()->GetName(), historyInfo->GetNZBInfo()->GetDupeKey(), nzbName, dupeKey)) { - g_pHistoryCoordinator->HistoryHide(pDownloadQueue, pHistoryInfo, index); + g_pHistoryCoordinator->HistoryHide(downloadQueue, historyInfo, index); index++; - it = pDownloadQueue->GetHistory()->rbegin() + index; - bChanged = true; + it = downloadQueue->GetHistory()->rbegin() + index; + changed = true; } else { @@ -519,94 +519,94 @@ void DupeCoordinator::HistoryCleanup(DownloadQueue* pDownloadQueue, HistoryInfo* } } - if (bChanged) + if (changed) { - pDownloadQueue->Save(); + downloadQueue->Save(); } } -DupeCoordinator::EDupeStatus DupeCoordinator::GetDupeStatus(DownloadQueue* pDownloadQueue, - const char* szName, const char* szDupeKey) +DupeCoordinator::EDupeStatus DupeCoordinator::GetDupeStatus(DownloadQueue* downloadQueue, + const char* name, const char* dupeKey) { - EDupeStatus eStatuses = dsNone; + EDupeStatus statuses = dsNone; // find duplicates in download queue - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - if (SameNameOrKey(szName, szDupeKey, pNZBInfo->GetName(), pNZBInfo->GetDupeKey())) + NZBInfo* nzbInfo = *it; + if (SameNameOrKey(name, dupeKey, nzbInfo->GetName(), nzbInfo->GetDupeKey())) { - if (pNZBInfo->GetSuccessArticles() + pNZBInfo->GetFailedArticles() > 0) + if (nzbInfo->GetSuccessArticles() + nzbInfo->GetFailedArticles() > 0) { - eStatuses = (EDupeStatus)(eStatuses | dsDownloading); + statuses = (EDupeStatus)(statuses | dsDownloading); } else { - eStatuses = (EDupeStatus)(eStatuses | dsQueued); + statuses = (EDupeStatus)(statuses | dsQueued); } } } // find duplicates in history - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; + HistoryInfo* historyInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - SameNameOrKey(szName, szDupeKey, pHistoryInfo->GetNZBInfo()->GetName(), pHistoryInfo->GetNZBInfo()->GetDupeKey())) + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + SameNameOrKey(name, dupeKey, historyInfo->GetNZBInfo()->GetName(), historyInfo->GetNZBInfo()->GetDupeKey())) { - const char* szTextStatus = pHistoryInfo->GetNZBInfo()->MakeTextStatus(true); - if (!strncasecmp(szTextStatus, "SUCCESS", 7)) + const char* textStatus = historyInfo->GetNZBInfo()->MakeTextStatus(true); + if (!strncasecmp(textStatus, "SUCCESS", 7)) { - eStatuses = (EDupeStatus)(eStatuses | dsSuccess); + statuses = (EDupeStatus)(statuses | dsSuccess); } - else if (!strncasecmp(szTextStatus, "FAILURE", 7)) + else if (!strncasecmp(textStatus, "FAILURE", 7)) { - eStatuses = (EDupeStatus)(eStatuses | dsFailure); + statuses = (EDupeStatus)(statuses | dsFailure); } - else if (!strncasecmp(szTextStatus, "WARNING", 7)) + else if (!strncasecmp(textStatus, "WARNING", 7)) { - eStatuses = (EDupeStatus)(eStatuses | dsWarning); + statuses = (EDupeStatus)(statuses | dsWarning); } } - if (pHistoryInfo->GetKind() == HistoryInfo::hkDup && - SameNameOrKey(szName, szDupeKey, pHistoryInfo->GetDupInfo()->GetName(), pHistoryInfo->GetDupInfo()->GetDupeKey())) + if (historyInfo->GetKind() == HistoryInfo::hkDup && + SameNameOrKey(name, dupeKey, historyInfo->GetDupInfo()->GetName(), historyInfo->GetDupInfo()->GetDupeKey())) { - if (pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsSuccess || - pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood) + if (historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsSuccess || + historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsGood) { - eStatuses = (EDupeStatus)(eStatuses | dsSuccess); + statuses = (EDupeStatus)(statuses | dsSuccess); } - else if (pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsFailed || - pHistoryInfo->GetDupInfo()->GetStatus() == DupInfo::dsBad) + else if (historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsFailed || + historyInfo->GetDupInfo()->GetStatus() == DupInfo::dsBad) { - eStatuses = (EDupeStatus)(eStatuses | dsFailure); + statuses = (EDupeStatus)(statuses | dsFailure); } } } - return eStatuses; + return statuses; } -void DupeCoordinator::ListHistoryDupes(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, NZBList* pDupeList) +void DupeCoordinator::ListHistoryDupes(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, NZBList* dupeList) { - if (pNZBInfo->GetDupeMode() == dmForce) + if (nzbInfo->GetDupeMode() == dmForce) { return; } // find duplicates in history - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; + HistoryInfo* historyInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && - pHistoryInfo->GetNZBInfo()->GetDupeMode() != dmForce && - SameNameOrKey(pHistoryInfo->GetNZBInfo()->GetName(), pHistoryInfo->GetNZBInfo()->GetDupeKey(), - pNZBInfo->GetName(), pNZBInfo->GetDupeKey())) + if (historyInfo->GetKind() == HistoryInfo::hkNzb && + historyInfo->GetNZBInfo()->GetDupeMode() != dmForce && + SameNameOrKey(historyInfo->GetNZBInfo()->GetName(), historyInfo->GetNZBInfo()->GetDupeKey(), + nzbInfo->GetName(), nzbInfo->GetDupeKey())) { - pDupeList->push_back(pHistoryInfo->GetNZBInfo()); + dupeList->push_back(historyInfo->GetNZBInfo()); } } } diff --git a/daemon/queue/DupeCoordinator.h b/daemon/queue/DupeCoordinator.h index f28d5233..6ad43436 100644 --- a/daemon/queue/DupeCoordinator.h +++ b/daemon/queue/DupeCoordinator.h @@ -42,16 +42,16 @@ public: }; private: - void ReturnBestDupe(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szNZBName, const char* szDupeKey); - void HistoryCleanup(DownloadQueue* pDownloadQueue, HistoryInfo* pMarkHistoryInfo); - bool SameNameOrKey(const char* szName1, const char* szDupeKey1, const char* szName2, const char* szDupeKey2); + void ReturnBestDupe(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* nzbName, const char* dupeKey); + void HistoryCleanup(DownloadQueue* downloadQueue, HistoryInfo* markHistoryInfo); + bool SameNameOrKey(const char* name1, const char* dupeKey1, const char* name2, const char* dupeKey2); public: - void NZBCompleted(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); - void NZBFound(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); - void HistoryMark(DownloadQueue* pDownloadQueue, HistoryInfo* pHistoryInfo, NZBInfo::EMarkStatus eMarkStatus); - EDupeStatus GetDupeStatus(DownloadQueue* pDownloadQueue, const char* szName, const char* szDupeKey); - void ListHistoryDupes(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, NZBList* pDupeList); + void NZBCompleted(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); + void NZBFound(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); + void HistoryMark(DownloadQueue* downloadQueue, HistoryInfo* historyInfo, NZBInfo::EMarkStatus markStatus); + EDupeStatus GetDupeStatus(DownloadQueue* downloadQueue, const char* name, const char* dupeKey); + void ListHistoryDupes(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, NZBList* dupeList); }; extern DupeCoordinator* g_pDupeCoordinator; diff --git a/daemon/queue/HistoryCoordinator.cpp b/daemon/queue/HistoryCoordinator.cpp index d702464c..1253677b 100644 --- a/daemon/queue/HistoryCoordinator.cpp +++ b/daemon/queue/HistoryCoordinator.cpp @@ -70,43 +70,43 @@ HistoryCoordinator::~HistoryCoordinator() */ void HistoryCoordinator::ServiceWork() { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - time_t tMinTime = time(NULL) - g_pOptions->GetKeepHistory() * 60*60*24; - bool bChanged = false; + time_t minTime = time(NULL) - g_pOptions->GetKeepHistory() * 60*60*24; + bool changed = false; int index = 0; // traversing in a reverse order to delete items in order they were added to history // (just to produce the log-messages in a more logical order) - for (HistoryList::reverse_iterator it = pDownloadQueue->GetHistory()->rbegin(); it != pDownloadQueue->GetHistory()->rend(); ) + for (HistoryList::reverse_iterator it = downloadQueue->GetHistory()->rbegin(); it != downloadQueue->GetHistory()->rend(); ) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() != HistoryInfo::hkDup && pHistoryInfo->GetTime() < tMinTime) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() != HistoryInfo::hkDup && historyInfo->GetTime() < minTime) { - if (g_pOptions->GetDupeCheck() && pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + if (g_pOptions->GetDupeCheck() && historyInfo->GetKind() == HistoryInfo::hkNzb) { // replace history element - HistoryHide(pDownloadQueue, pHistoryInfo, index); + HistoryHide(downloadQueue, historyInfo, index); index++; } else { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); - pDownloadQueue->GetHistory()->erase(pDownloadQueue->GetHistory()->end() - 1 - index); + downloadQueue->GetHistory()->erase(downloadQueue->GetHistory()->end() - 1 - index); - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { - DeleteDiskFiles(pHistoryInfo->GetNZBInfo()); + DeleteDiskFiles(historyInfo->GetNZBInfo()); } - info("Collection %s removed from history", szNiceName); + info("Collection %s removed from history", niceName); - delete pHistoryInfo; + delete historyInfo; } - it = pDownloadQueue->GetHistory()->rbegin() + index; - bChanged = true; + it = downloadQueue->GetHistory()->rbegin() + index; + changed = true; } else { @@ -115,22 +115,22 @@ void HistoryCoordinator::ServiceWork() } } - if (bChanged) + if (changed) { - pDownloadQueue->Save(); + downloadQueue->Save(); } DownloadQueue::Unlock(); } -void HistoryCoordinator::DeleteDiskFiles(NZBInfo* pNZBInfo) +void HistoryCoordinator::DeleteDiskFiles(NZBInfo* nzbInfo) { if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) { // delete parked files - g_pDiskState->DiscardFiles(pNZBInfo); + g_pDiskState->DiscardFiles(nzbInfo); } - pNZBInfo->GetFileList()->Clear(); + nzbInfo->GetFileList()->Clear(); // delete nzb-file if (!g_pOptions->GetNzbCleanupDisk()) @@ -140,191 +140,191 @@ void HistoryCoordinator::DeleteDiskFiles(NZBInfo* pNZBInfo) // QueuedFile may contain one filename or several filenames separated // with "|"-character (for merged groups) - char* szFilename = strdup(pNZBInfo->GetQueuedFilename()); - char* szEnd = szFilename - 1; + char* filename = strdup(nzbInfo->GetQueuedFilename()); + char* end = filename - 1; - while (szEnd) + while (end) { - char* szName1 = szEnd + 1; - szEnd = strchr(szName1, '|'); - if (szEnd) *szEnd = '\0'; + char* name1 = end + 1; + end = strchr(name1, '|'); + if (end) *end = '\0'; - if (Util::FileExists(szName1)) + if (Util::FileExists(name1)) { - info("Deleting file %s", szName1); - remove(szName1); + info("Deleting file %s", name1); + remove(name1); } } - free(szFilename); + free(filename); } -void HistoryCoordinator::AddToHistory(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo) +void HistoryCoordinator::AddToHistory(DownloadQueue* downloadQueue, NZBInfo* nzbInfo) { //remove old item for the same NZB - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetNZBInfo() == pNZBInfo) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetNZBInfo() == nzbInfo) { - delete pHistoryInfo; - pDownloadQueue->GetHistory()->erase(it); + delete historyInfo; + downloadQueue->GetHistory()->erase(it); break; } } - HistoryInfo* pHistoryInfo = new HistoryInfo(pNZBInfo); - pHistoryInfo->SetTime(time(NULL)); - pDownloadQueue->GetHistory()->push_front(pHistoryInfo); - pDownloadQueue->GetQueue()->Remove(pNZBInfo); + HistoryInfo* historyInfo = new HistoryInfo(nzbInfo); + historyInfo->SetTime(time(NULL)); + downloadQueue->GetHistory()->push_front(historyInfo); + downloadQueue->GetQueue()->Remove(nzbInfo); - if (pNZBInfo->GetDeleteStatus() == NZBInfo::dsNone) + if (nzbInfo->GetDeleteStatus() == NZBInfo::dsNone) { // park files and delete files marked for deletion - int iParkedFiles = 0; - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); ) + int parkedFiles = 0; + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); ) { - FileInfo* pFileInfo = *it; - if (!pFileInfo->GetDeleted()) + FileInfo* fileInfo = *it; + if (!fileInfo->GetDeleted()) { - detail("Parking file %s", pFileInfo->GetFilename()); - g_pQueueCoordinator->DiscardDiskFile(pFileInfo); - iParkedFiles++; + detail("Parking file %s", fileInfo->GetFilename()); + g_pQueueCoordinator->DiscardDiskFile(fileInfo); + parkedFiles++; it++; } else { // since we removed pNZBInfo from queue we need to take care of removing file infos marked for deletion - pNZBInfo->GetFileList()->erase(it); - delete pFileInfo; - it = pNZBInfo->GetFileList()->begin() + iParkedFiles; + nzbInfo->GetFileList()->erase(it); + delete fileInfo; + it = nzbInfo->GetFileList()->begin() + parkedFiles; } } - pNZBInfo->SetParkedFileCount(iParkedFiles); + nzbInfo->SetParkedFileCount(parkedFiles); } else { - pNZBInfo->GetFileList()->Clear(); + nzbInfo->GetFileList()->Clear(); } - pNZBInfo->PrintMessage(Message::mkInfo, "Collection %s added to history", pNZBInfo->GetName()); + nzbInfo->PrintMessage(Message::mkInfo, "Collection %s added to history", nzbInfo->GetName()); } -void HistoryCoordinator::HistoryHide(DownloadQueue* pDownloadQueue, HistoryInfo* pHistoryInfo, int rindex) +void HistoryCoordinator::HistoryHide(DownloadQueue* downloadQueue, HistoryInfo* historyInfo, int rindex) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); // replace history element - DupInfo* pDupInfo = new DupInfo(); - pDupInfo->SetID(pHistoryInfo->GetNZBInfo()->GetID()); - pDupInfo->SetName(pHistoryInfo->GetNZBInfo()->GetName()); - pDupInfo->SetDupeKey(pHistoryInfo->GetNZBInfo()->GetDupeKey()); - pDupInfo->SetDupeScore(pHistoryInfo->GetNZBInfo()->GetDupeScore()); - pDupInfo->SetDupeMode(pHistoryInfo->GetNZBInfo()->GetDupeMode()); - pDupInfo->SetSize(pHistoryInfo->GetNZBInfo()->GetSize()); - pDupInfo->SetFullContentHash(pHistoryInfo->GetNZBInfo()->GetFullContentHash()); - pDupInfo->SetFilteredContentHash(pHistoryInfo->GetNZBInfo()->GetFilteredContentHash()); + DupInfo* dupInfo = new DupInfo(); + dupInfo->SetID(historyInfo->GetNZBInfo()->GetID()); + dupInfo->SetName(historyInfo->GetNZBInfo()->GetName()); + dupInfo->SetDupeKey(historyInfo->GetNZBInfo()->GetDupeKey()); + dupInfo->SetDupeScore(historyInfo->GetNZBInfo()->GetDupeScore()); + dupInfo->SetDupeMode(historyInfo->GetNZBInfo()->GetDupeMode()); + dupInfo->SetSize(historyInfo->GetNZBInfo()->GetSize()); + dupInfo->SetFullContentHash(historyInfo->GetNZBInfo()->GetFullContentHash()); + dupInfo->SetFilteredContentHash(historyInfo->GetNZBInfo()->GetFilteredContentHash()); - pDupInfo->SetStatus( - pHistoryInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksGood ? DupInfo::dsGood : - pHistoryInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksBad ? DupInfo::dsBad : - pHistoryInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksSuccess ? DupInfo::dsSuccess : - pHistoryInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsDupe ? DupInfo::dsDupe : - pHistoryInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsManual || - pHistoryInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsGood || - pHistoryInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsCopy ? DupInfo::dsDeleted : - pHistoryInfo->GetNZBInfo()->IsDupeSuccess() ? DupInfo::dsSuccess : + dupInfo->SetStatus( + historyInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksGood ? DupInfo::dsGood : + historyInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksBad ? DupInfo::dsBad : + historyInfo->GetNZBInfo()->GetMarkStatus() == NZBInfo::ksSuccess ? DupInfo::dsSuccess : + historyInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsDupe ? DupInfo::dsDupe : + historyInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsManual || + historyInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsGood || + historyInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsCopy ? DupInfo::dsDeleted : + historyInfo->GetNZBInfo()->IsDupeSuccess() ? DupInfo::dsSuccess : DupInfo::dsFailed); - HistoryInfo* pNewHistoryInfo = new HistoryInfo(pDupInfo); - pNewHistoryInfo->SetTime(pHistoryInfo->GetTime()); - (*pDownloadQueue->GetHistory())[pDownloadQueue->GetHistory()->size() - 1 - rindex] = pNewHistoryInfo; + HistoryInfo* newHistoryInfo = new HistoryInfo(dupInfo); + newHistoryInfo->SetTime(historyInfo->GetTime()); + (*downloadQueue->GetHistory())[downloadQueue->GetHistory()->size() - 1 - rindex] = newHistoryInfo; - DeleteDiskFiles(pHistoryInfo->GetNZBInfo()); + DeleteDiskFiles(historyInfo->GetNZBInfo()); - delete pHistoryInfo; - info("Collection %s removed from history", szNiceName); + delete historyInfo; + info("Collection %s removed from history", niceName); } -void HistoryCoordinator::PrepareEdit(DownloadQueue* pDownloadQueue, IDList* pIDList, DownloadQueue::EEditAction eAction) +void HistoryCoordinator::PrepareEdit(DownloadQueue* downloadQueue, IDList* idList, DownloadQueue::EEditAction action) { // First pass: when marking multiple items - mark them bad without performing the mark-logic, // this will later (on second step) avoid moving other items to download queue, if they are marked bad too. - if (eAction == DownloadQueue::eaHistoryMarkBad) + if (action == DownloadQueue::eaHistoryMarkBad) { - for (IDList::iterator itID = pIDList->begin(); itID != pIDList->end(); itID++) + for (IDList::iterator itID = idList->begin(); itID != idList->end(); itID++) { - int iID = *itID; - HistoryInfo* pHistoryInfo = pDownloadQueue->GetHistory()->Find(iID); - if (pHistoryInfo && pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + int id = *itID; + HistoryInfo* historyInfo = downloadQueue->GetHistory()->Find(id); + if (historyInfo && historyInfo->GetKind() == HistoryInfo::hkNzb) { - pHistoryInfo->GetNZBInfo()->SetMarkStatus(NZBInfo::ksBad); + historyInfo->GetNZBInfo()->SetMarkStatus(NZBInfo::ksBad); } } } } -bool HistoryCoordinator::EditList(DownloadQueue* pDownloadQueue, IDList* pIDList, DownloadQueue::EEditAction eAction, int iOffset, const char* szText) +bool HistoryCoordinator::EditList(DownloadQueue* downloadQueue, IDList* idList, DownloadQueue::EEditAction action, int offset, const char* text) { - bool bOK = false; - PrepareEdit(pDownloadQueue, pIDList, eAction); + bool ok = false; + PrepareEdit(downloadQueue, idList, action); - for (IDList::iterator itID = pIDList->begin(); itID != pIDList->end(); itID++) + for (IDList::iterator itID = idList->begin(); itID != idList->end(); itID++) { - int iID = *itID; - for (HistoryList::iterator itHistory = pDownloadQueue->GetHistory()->begin(); itHistory != pDownloadQueue->GetHistory()->end(); itHistory++) + int id = *itID; + for (HistoryList::iterator itHistory = downloadQueue->GetHistory()->begin(); itHistory != downloadQueue->GetHistory()->end(); itHistory++) { - HistoryInfo* pHistoryInfo = *itHistory; - if (pHistoryInfo->GetID() == iID) + HistoryInfo* historyInfo = *itHistory; + if (historyInfo->GetID() == id) { - bOK = true; + ok = true; - switch (eAction) + switch (action) { case DownloadQueue::eaHistoryDelete: case DownloadQueue::eaHistoryFinalDelete: - HistoryDelete(pDownloadQueue, itHistory, pHistoryInfo, eAction == DownloadQueue::eaHistoryFinalDelete); + HistoryDelete(downloadQueue, itHistory, historyInfo, action == DownloadQueue::eaHistoryFinalDelete); break; case DownloadQueue::eaHistoryReturn: case DownloadQueue::eaHistoryProcess: - HistoryReturn(pDownloadQueue, itHistory, pHistoryInfo, eAction == DownloadQueue::eaHistoryProcess); + HistoryReturn(downloadQueue, itHistory, historyInfo, action == DownloadQueue::eaHistoryProcess); break; case DownloadQueue::eaHistoryRedownload: - HistoryRedownload(pDownloadQueue, itHistory, pHistoryInfo, false); + HistoryRedownload(downloadQueue, itHistory, historyInfo, false); break; case DownloadQueue::eaHistorySetParameter: - bOK = HistorySetParameter(pHistoryInfo, szText); + ok = HistorySetParameter(historyInfo, text); break; case DownloadQueue::eaHistorySetCategory: - bOK = HistorySetCategory(pHistoryInfo, szText); + ok = HistorySetCategory(historyInfo, text); break; case DownloadQueue::eaHistorySetName: - bOK = HistorySetName(pHistoryInfo, szText); + ok = HistorySetName(historyInfo, text); break; case DownloadQueue::eaHistorySetDupeKey: case DownloadQueue::eaHistorySetDupeScore: case DownloadQueue::eaHistorySetDupeMode: case DownloadQueue::eaHistorySetDupeBackup: - HistorySetDupeParam(pHistoryInfo, eAction, szText); + HistorySetDupeParam(historyInfo, action, text); break; case DownloadQueue::eaHistoryMarkBad: - g_pDupeCoordinator->HistoryMark(pDownloadQueue, pHistoryInfo, NZBInfo::ksBad); + g_pDupeCoordinator->HistoryMark(downloadQueue, historyInfo, NZBInfo::ksBad); break; case DownloadQueue::eaHistoryMarkGood: - g_pDupeCoordinator->HistoryMark(pDownloadQueue, pHistoryInfo, NZBInfo::ksGood); + g_pDupeCoordinator->HistoryMark(downloadQueue, historyInfo, NZBInfo::ksGood); break; case DownloadQueue::eaHistoryMarkSuccess: - g_pDupeCoordinator->HistoryMark(pDownloadQueue, pHistoryInfo, NZBInfo::ksSuccess); + g_pDupeCoordinator->HistoryMark(downloadQueue, historyInfo, NZBInfo::ksSuccess); break; default: @@ -337,370 +337,370 @@ bool HistoryCoordinator::EditList(DownloadQueue* pDownloadQueue, IDList* pIDList } } - if (bOK) + if (ok) { - pDownloadQueue->Save(); + downloadQueue->Save(); } - return bOK; + return ok; } -void HistoryCoordinator::HistoryDelete(DownloadQueue* pDownloadQueue, HistoryList::iterator itHistory, - HistoryInfo* pHistoryInfo, bool bFinal) +void HistoryCoordinator::HistoryDelete(DownloadQueue* downloadQueue, HistoryList::iterator itHistory, + HistoryInfo* historyInfo, bool final) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); - info("Deleting %s from history", szNiceName); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); + info("Deleting %s from history", niceName); - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { - DeleteDiskFiles(pHistoryInfo->GetNZBInfo()); + DeleteDiskFiles(historyInfo->GetNZBInfo()); } - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb && + if (historyInfo->GetKind() == HistoryInfo::hkNzb && g_pOptions->GetDeleteCleanupDisk() && - (pHistoryInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsNone || - pHistoryInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psFailure || - pHistoryInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usFailure || - pHistoryInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usPassword) && - Util::DirectoryExists(pHistoryInfo->GetNZBInfo()->GetDestDir())) + (historyInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsNone || + historyInfo->GetNZBInfo()->GetParStatus() == NZBInfo::psFailure || + historyInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usFailure || + historyInfo->GetNZBInfo()->GetUnpackStatus() == NZBInfo::usPassword) && + Util::DirectoryExists(historyInfo->GetNZBInfo()->GetDestDir())) { - info("Deleting %s", pHistoryInfo->GetNZBInfo()->GetDestDir()); - char szErrBuf[256]; - if (!Util::DeleteDirectoryWithContent(pHistoryInfo->GetNZBInfo()->GetDestDir(), szErrBuf, sizeof(szErrBuf))) + info("Deleting %s", historyInfo->GetNZBInfo()->GetDestDir()); + char errBuf[256]; + if (!Util::DeleteDirectoryWithContent(historyInfo->GetNZBInfo()->GetDestDir(), errBuf, sizeof(errBuf))) { - error("Could not delete directory %s: %s", pHistoryInfo->GetNZBInfo()->GetDestDir(), szErrBuf); + error("Could not delete directory %s: %s", historyInfo->GetNZBInfo()->GetDestDir(), errBuf); } } - if (bFinal || !g_pOptions->GetDupeCheck() || pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (final || !g_pOptions->GetDupeCheck() || historyInfo->GetKind() == HistoryInfo::hkUrl) { - pDownloadQueue->GetHistory()->erase(itHistory); - delete pHistoryInfo; + downloadQueue->GetHistory()->erase(itHistory); + delete historyInfo; } else { - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { // replace history element - int rindex = pDownloadQueue->GetHistory()->size() - 1 - (itHistory - pDownloadQueue->GetHistory()->begin()); - HistoryHide(pDownloadQueue, pHistoryInfo, rindex); + int rindex = downloadQueue->GetHistory()->size() - 1 - (itHistory - downloadQueue->GetHistory()->begin()); + HistoryHide(downloadQueue, historyInfo, rindex); } } } -void HistoryCoordinator::HistoryReturn(DownloadQueue* pDownloadQueue, HistoryList::iterator itHistory, HistoryInfo* pHistoryInfo, bool bReprocess) +void HistoryCoordinator::HistoryReturn(DownloadQueue* downloadQueue, HistoryList::iterator itHistory, HistoryInfo* historyInfo, bool reprocess) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); - debug("Returning %s from history back to download queue", szNiceName); - NZBInfo* pNZBInfo = NULL; + char niceName[1024]; + historyInfo->GetName(niceName, 1024); + debug("Returning %s from history back to download queue", niceName); + NZBInfo* nzbInfo = NULL; - if (bReprocess && pHistoryInfo->GetKind() != HistoryInfo::hkNzb) + if (reprocess && historyInfo->GetKind() != HistoryInfo::hkNzb) { - error("Could not restart postprocessing for %s: history item has wrong type", szNiceName); + error("Could not restart postprocessing for %s: history item has wrong type", niceName); return; } - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { - pNZBInfo = pHistoryInfo->GetNZBInfo(); + nzbInfo = historyInfo->GetNZBInfo(); // unpark files - bool bUnparked = false; - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + bool unparked = false; + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - detail("Unpark file %s", pFileInfo->GetFilename()); - bUnparked = true; + FileInfo* fileInfo = *it; + detail("Unpark file %s", fileInfo->GetFilename()); + unparked = true; } - if (!(bUnparked || bReprocess)) + if (!(unparked || reprocess)) { - warn("Could not return %s back from history to download queue: history item does not have any files left for download", szNiceName); + warn("Could not return %s back from history to download queue: history item does not have any files left for download", niceName); return; } - pDownloadQueue->GetQueue()->push_front(pNZBInfo); - pHistoryInfo->DiscardNZBInfo(); + downloadQueue->GetQueue()->push_front(nzbInfo); + historyInfo->DiscardNZBInfo(); // reset postprocessing status variables - pNZBInfo->SetParCleanup(false); - if (!pNZBInfo->GetUnpackCleanedUpDisk()) + nzbInfo->SetParCleanup(false); + if (!nzbInfo->GetUnpackCleanedUpDisk()) { - pNZBInfo->SetUnpackStatus(NZBInfo::usNone); - pNZBInfo->SetCleanupStatus(NZBInfo::csNone); - pNZBInfo->SetRenameStatus(NZBInfo::rsNone); - pNZBInfo->SetPostTotalSec(pNZBInfo->GetPostTotalSec() - pNZBInfo->GetUnpackSec()); - pNZBInfo->SetUnpackSec(0); + nzbInfo->SetUnpackStatus(NZBInfo::usNone); + nzbInfo->SetCleanupStatus(NZBInfo::csNone); + nzbInfo->SetRenameStatus(NZBInfo::rsNone); + nzbInfo->SetPostTotalSec(nzbInfo->GetPostTotalSec() - nzbInfo->GetUnpackSec()); + nzbInfo->SetUnpackSec(0); - if (ParParser::FindMainPars(pNZBInfo->GetDestDir(), NULL)) + if (ParParser::FindMainPars(nzbInfo->GetDestDir(), NULL)) { - pNZBInfo->SetParStatus(NZBInfo::psNone); - pNZBInfo->SetPostTotalSec(pNZBInfo->GetPostTotalSec() - pNZBInfo->GetParSec()); - pNZBInfo->SetParSec(0); - pNZBInfo->SetRepairSec(0); - pNZBInfo->SetParFull(false); + nzbInfo->SetParStatus(NZBInfo::psNone); + nzbInfo->SetPostTotalSec(nzbInfo->GetPostTotalSec() - nzbInfo->GetParSec()); + nzbInfo->SetParSec(0); + nzbInfo->SetRepairSec(0); + nzbInfo->SetParFull(false); } } - pNZBInfo->SetDeleteStatus(NZBInfo::dsNone); - pNZBInfo->SetDeletePaused(false); - pNZBInfo->SetMarkStatus(NZBInfo::ksNone); - pNZBInfo->GetScriptStatuses()->Clear(); - pNZBInfo->SetParkedFileCount(0); - if (pNZBInfo->GetMoveStatus() == NZBInfo::msFailure) + nzbInfo->SetDeleteStatus(NZBInfo::dsNone); + nzbInfo->SetDeletePaused(false); + nzbInfo->SetMarkStatus(NZBInfo::ksNone); + nzbInfo->GetScriptStatuses()->Clear(); + nzbInfo->SetParkedFileCount(0); + if (nzbInfo->GetMoveStatus() == NZBInfo::msFailure) { - pNZBInfo->SetMoveStatus(NZBInfo::msNone); + nzbInfo->SetMoveStatus(NZBInfo::msNone); } - pNZBInfo->SetReprocess(bReprocess); + nzbInfo->SetReprocess(reprocess); } - if (pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkUrl) { - pNZBInfo = pHistoryInfo->GetNZBInfo(); - pHistoryInfo->DiscardNZBInfo(); - pNZBInfo->SetUrlStatus(NZBInfo::lsNone); - pNZBInfo->SetDeleteStatus(NZBInfo::dsNone); - pDownloadQueue->GetQueue()->push_front(pNZBInfo); + nzbInfo = historyInfo->GetNZBInfo(); + historyInfo->DiscardNZBInfo(); + nzbInfo->SetUrlStatus(NZBInfo::lsNone); + nzbInfo->SetDeleteStatus(NZBInfo::dsNone); + downloadQueue->GetQueue()->push_front(nzbInfo); } - pDownloadQueue->GetHistory()->erase(itHistory); + downloadQueue->GetHistory()->erase(itHistory); // the object "pHistoryInfo" is released few lines later, after the call to "NZBDownloaded" - pNZBInfo->PrintMessage(Message::mkInfo, "%s returned from history back to download queue", szNiceName); + nzbInfo->PrintMessage(Message::mkInfo, "%s returned from history back to download queue", niceName); - if (bReprocess) + if (reprocess) { // start postprocessing - debug("Restarting postprocessing for %s", szNiceName); - g_pPrePostProcessor->NZBDownloaded(pDownloadQueue, pNZBInfo); + debug("Restarting postprocessing for %s", niceName); + g_pPrePostProcessor->NZBDownloaded(downloadQueue, nzbInfo); } - delete pHistoryInfo; + delete historyInfo; } -void HistoryCoordinator::HistoryRedownload(DownloadQueue* pDownloadQueue, HistoryList::iterator itHistory, - HistoryInfo* pHistoryInfo, bool bRestorePauseState) +void HistoryCoordinator::HistoryRedownload(DownloadQueue* downloadQueue, HistoryList::iterator itHistory, + HistoryInfo* historyInfo, bool restorePauseState) { - if (pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkUrl) { - HistoryReturn(pDownloadQueue, itHistory, pHistoryInfo, false); + HistoryReturn(downloadQueue, itHistory, historyInfo, false); return; } - if (pHistoryInfo->GetKind() != HistoryInfo::hkNzb) + if (historyInfo->GetKind() != HistoryInfo::hkNzb) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); - error("Could not return %s from history back to queue: history item has wrong type", szNiceName); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); + error("Could not return %s from history back to queue: history item has wrong type", niceName); return; } - NZBInfo* pNZBInfo = pHistoryInfo->GetNZBInfo(); - bool bPaused = bRestorePauseState && pNZBInfo->GetDeletePaused(); + NZBInfo* nzbInfo = historyInfo->GetNZBInfo(); + bool paused = restorePauseState && nzbInfo->GetDeletePaused(); - if (!Util::FileExists(pNZBInfo->GetQueuedFilename())) + if (!Util::FileExists(nzbInfo->GetQueuedFilename())) { error("Could not return %s from history back to queue: could not find source nzb-file %s", - pNZBInfo->GetName(), pNZBInfo->GetQueuedFilename()); + nzbInfo->GetName(), nzbInfo->GetQueuedFilename()); return; } - NZBFile* pNZBFile = new NZBFile(pNZBInfo->GetQueuedFilename(), ""); - if (!pNZBFile->Parse()) + NZBFile* nzbFile = new NZBFile(nzbInfo->GetQueuedFilename(), ""); + if (!nzbFile->Parse()) { error("Could not return %s from history back to queue: could not parse nzb-file", - pNZBInfo->GetName()); - delete pNZBFile; + nzbInfo->GetName()); + delete nzbFile; return; } - info("Returning %s from history back to queue", pNZBInfo->GetName()); + info("Returning %s from history back to queue", nzbInfo->GetName()); - for (FileList::iterator it = pNZBFile->GetNZBInfo()->GetFileList()->begin(); it != pNZBFile->GetNZBInfo()->GetFileList()->end(); it++) + for (FileList::iterator it = nzbFile->GetNZBInfo()->GetFileList()->begin(); it != nzbFile->GetNZBInfo()->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - pFileInfo->SetPaused(bPaused); + FileInfo* fileInfo = *it; + fileInfo->SetPaused(paused); } - if (Util::DirectoryExists(pNZBInfo->GetDestDir())) + if (Util::DirectoryExists(nzbInfo->GetDestDir())) { - detail("Deleting %s", pNZBInfo->GetDestDir()); - char szErrBuf[256]; - if (!Util::DeleteDirectoryWithContent(pNZBInfo->GetDestDir(), szErrBuf, sizeof(szErrBuf))) + detail("Deleting %s", nzbInfo->GetDestDir()); + char errBuf[256]; + if (!Util::DeleteDirectoryWithContent(nzbInfo->GetDestDir(), errBuf, sizeof(errBuf))) { - error("Could not delete directory %s: %s", pNZBInfo->GetDestDir(), szErrBuf); + error("Could not delete directory %s: %s", nzbInfo->GetDestDir(), errBuf); } } - pNZBInfo->BuildDestDirName(); - if (Util::DirectoryExists(pNZBInfo->GetDestDir())) + nzbInfo->BuildDestDirName(); + if (Util::DirectoryExists(nzbInfo->GetDestDir())) { - detail("Deleting %s", pNZBInfo->GetDestDir()); - char szErrBuf[256]; - if (!Util::DeleteDirectoryWithContent(pNZBInfo->GetDestDir(), szErrBuf, sizeof(szErrBuf))) + detail("Deleting %s", nzbInfo->GetDestDir()); + char errBuf[256]; + if (!Util::DeleteDirectoryWithContent(nzbInfo->GetDestDir(), errBuf, sizeof(errBuf))) { - error("Could not delete directory %s: %s", pNZBInfo->GetDestDir(), szErrBuf); + error("Could not delete directory %s: %s", nzbInfo->GetDestDir(), errBuf); } } - g_pDiskState->DiscardFiles(pNZBInfo); + g_pDiskState->DiscardFiles(nzbInfo); // reset status fields (which are not reset by "HistoryReturn") - pNZBInfo->SetMoveStatus(NZBInfo::msNone); - pNZBInfo->SetUnpackCleanedUpDisk(false); - pNZBInfo->SetParStatus(NZBInfo::psNone); - pNZBInfo->SetRenameStatus(NZBInfo::rsNone); - pNZBInfo->SetDownloadedSize(0); - pNZBInfo->SetDownloadSec(0); - pNZBInfo->SetPostTotalSec(0); - pNZBInfo->SetParSec(0); - pNZBInfo->SetRepairSec(0); - pNZBInfo->SetUnpackSec(0); - pNZBInfo->SetExtraParBlocks(0); - pNZBInfo->ClearCompletedFiles(); - pNZBInfo->GetServerStats()->Clear(); - pNZBInfo->GetCurrentServerStats()->Clear(); + nzbInfo->SetMoveStatus(NZBInfo::msNone); + nzbInfo->SetUnpackCleanedUpDisk(false); + nzbInfo->SetParStatus(NZBInfo::psNone); + nzbInfo->SetRenameStatus(NZBInfo::rsNone); + nzbInfo->SetDownloadedSize(0); + nzbInfo->SetDownloadSec(0); + nzbInfo->SetPostTotalSec(0); + nzbInfo->SetParSec(0); + nzbInfo->SetRepairSec(0); + nzbInfo->SetUnpackSec(0); + nzbInfo->SetExtraParBlocks(0); + nzbInfo->ClearCompletedFiles(); + nzbInfo->GetServerStats()->Clear(); + nzbInfo->GetCurrentServerStats()->Clear(); - pNZBInfo->CopyFileList(pNZBFile->GetNZBInfo()); + nzbInfo->CopyFileList(nzbFile->GetNZBInfo()); - g_pQueueCoordinator->CheckDupeFileInfos(pNZBInfo); - delete pNZBFile; + g_pQueueCoordinator->CheckDupeFileInfos(nzbInfo); + delete nzbFile; - HistoryReturn(pDownloadQueue, itHistory, pHistoryInfo, false); + HistoryReturn(downloadQueue, itHistory, historyInfo, false); - g_pPrePostProcessor->NZBAdded(pDownloadQueue, pNZBInfo); + g_pPrePostProcessor->NZBAdded(downloadQueue, nzbInfo); } -bool HistoryCoordinator::HistorySetParameter(HistoryInfo* pHistoryInfo, const char* szText) +bool HistoryCoordinator::HistorySetParameter(HistoryInfo* historyInfo, const char* text) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); - debug("Setting post-process-parameter '%s' for '%s'", szText, szNiceName); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); + debug("Setting post-process-parameter '%s' for '%s'", text, niceName); - if (!(pHistoryInfo->GetKind() == HistoryInfo::hkNzb || pHistoryInfo->GetKind() == HistoryInfo::hkUrl)) + if (!(historyInfo->GetKind() == HistoryInfo::hkNzb || historyInfo->GetKind() == HistoryInfo::hkUrl)) { - error("Could not set post-process-parameter for %s: history item has wrong type", szNiceName); + error("Could not set post-process-parameter for %s: history item has wrong type", niceName); return false; } - char* szStr = strdup(szText); + char* str = strdup(text); - char* szValue = strchr(szStr, '='); - if (szValue) + char* value = strchr(str, '='); + if (value) { - *szValue = '\0'; - szValue++; - pHistoryInfo->GetNZBInfo()->GetParameters()->SetParameter(szStr, szValue); + *value = '\0'; + value++; + historyInfo->GetNZBInfo()->GetParameters()->SetParameter(str, value); } else { - error("Could not set post-process-parameter for %s: invalid argument: %s", pHistoryInfo->GetNZBInfo()->GetName(), szText); + error("Could not set post-process-parameter for %s: invalid argument: %s", historyInfo->GetNZBInfo()->GetName(), text); } - free(szStr); + free(str); return true; } -bool HistoryCoordinator::HistorySetCategory(HistoryInfo* pHistoryInfo, const char* szText) +bool HistoryCoordinator::HistorySetCategory(HistoryInfo* historyInfo, const char* text) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); - debug("Setting category '%s' for '%s'", szText, szNiceName); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); + debug("Setting category '%s' for '%s'", text, niceName); - if (!(pHistoryInfo->GetKind() == HistoryInfo::hkNzb || pHistoryInfo->GetKind() == HistoryInfo::hkUrl)) + if (!(historyInfo->GetKind() == HistoryInfo::hkNzb || historyInfo->GetKind() == HistoryInfo::hkUrl)) { - error("Could not set category for %s: history item has wrong type", szNiceName); + error("Could not set category for %s: history item has wrong type", niceName); return false; } - pHistoryInfo->GetNZBInfo()->SetCategory(szText); + historyInfo->GetNZBInfo()->SetCategory(text); return true; } -bool HistoryCoordinator::HistorySetName(HistoryInfo* pHistoryInfo, const char* szText) +bool HistoryCoordinator::HistorySetName(HistoryInfo* historyInfo, const char* text) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); - debug("Setting name '%s' for '%s'", szText, szNiceName); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); + debug("Setting name '%s' for '%s'", text, niceName); - if (Util::EmptyStr(szText)) + if (Util::EmptyStr(text)) { - error("Could not rename %s. The new name cannot be empty", szNiceName); + error("Could not rename %s. The new name cannot be empty", niceName); return false; } - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb || pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkNzb || historyInfo->GetKind() == HistoryInfo::hkUrl) { - pHistoryInfo->GetNZBInfo()->SetName(szText); + historyInfo->GetNZBInfo()->SetName(text); } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkDup) + else if (historyInfo->GetKind() == HistoryInfo::hkDup) { - pHistoryInfo->GetDupInfo()->SetName(szText); + historyInfo->GetDupInfo()->SetName(text); } return true; } -void HistoryCoordinator::HistorySetDupeParam(HistoryInfo* pHistoryInfo, DownloadQueue::EEditAction eAction, const char* szText) +void HistoryCoordinator::HistorySetDupeParam(HistoryInfo* historyInfo, DownloadQueue::EEditAction action, const char* text) { - char szNiceName[1024]; - pHistoryInfo->GetName(szNiceName, 1024); - debug("Setting dupe-parameter '%i'='%s' for '%s'", (int)eAction, szText, szNiceName); + char niceName[1024]; + historyInfo->GetName(niceName, 1024); + debug("Setting dupe-parameter '%i'='%s' for '%s'", (int)action, text, niceName); - EDupeMode eMode = dmScore; - if (eAction == DownloadQueue::eaHistorySetDupeMode) + EDupeMode mode = dmScore; + if (action == DownloadQueue::eaHistorySetDupeMode) { - if (!strcasecmp(szText, "SCORE")) + if (!strcasecmp(text, "SCORE")) { - eMode = dmScore; + mode = dmScore; } - else if (!strcasecmp(szText, "ALL")) + else if (!strcasecmp(text, "ALL")) { - eMode = dmAll; + mode = dmAll; } - else if (!strcasecmp(szText, "FORCE")) + else if (!strcasecmp(text, "FORCE")) { - eMode = dmForce; + mode = dmForce; } else { - error("Could not set duplicate mode for %s: incorrect mode (%s)", szNiceName, szText); + error("Could not set duplicate mode for %s: incorrect mode (%s)", niceName, text); return; } } - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb || pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkNzb || historyInfo->GetKind() == HistoryInfo::hkUrl) { - switch (eAction) + switch (action) { case DownloadQueue::eaHistorySetDupeKey: - pHistoryInfo->GetNZBInfo()->SetDupeKey(szText); + historyInfo->GetNZBInfo()->SetDupeKey(text); break; case DownloadQueue::eaHistorySetDupeScore: - pHistoryInfo->GetNZBInfo()->SetDupeScore(atoi(szText)); + historyInfo->GetNZBInfo()->SetDupeScore(atoi(text)); break; case DownloadQueue::eaHistorySetDupeMode: - pHistoryInfo->GetNZBInfo()->SetDupeMode(eMode); + historyInfo->GetNZBInfo()->SetDupeMode(mode); break; case DownloadQueue::eaHistorySetDupeBackup: - if (pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkUrl) { - error("Could not set duplicate parameter for %s: history item has wrong type", szNiceName); + error("Could not set duplicate parameter for %s: history item has wrong type", niceName); return; } - else if (pHistoryInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsDupe && - pHistoryInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsManual) + else if (historyInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsDupe && + historyInfo->GetNZBInfo()->GetDeleteStatus() != NZBInfo::dsManual) { - error("Could not set duplicate parameter for %s: history item has wrong delete status", szNiceName); + error("Could not set duplicate parameter for %s: history item has wrong delete status", niceName); return; } - pHistoryInfo->GetNZBInfo()->SetDeleteStatus(!strcasecmp(szText, "YES") || - !strcasecmp(szText, "TRUE") || !strcasecmp(szText, "1") ? NZBInfo::dsDupe : NZBInfo::dsManual); + historyInfo->GetNZBInfo()->SetDeleteStatus(!strcasecmp(text, "YES") || + !strcasecmp(text, "TRUE") || !strcasecmp(text, "1") ? NZBInfo::dsDupe : NZBInfo::dsManual); break; default: @@ -708,24 +708,24 @@ void HistoryCoordinator::HistorySetDupeParam(HistoryInfo* pHistoryInfo, Download break; } } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkDup) + else if (historyInfo->GetKind() == HistoryInfo::hkDup) { - switch (eAction) + switch (action) { case DownloadQueue::eaHistorySetDupeKey: - pHistoryInfo->GetDupInfo()->SetDupeKey(szText); + historyInfo->GetDupInfo()->SetDupeKey(text); break; case DownloadQueue::eaHistorySetDupeScore: - pHistoryInfo->GetDupInfo()->SetDupeScore(atoi(szText)); + historyInfo->GetDupInfo()->SetDupeScore(atoi(text)); break; case DownloadQueue::eaHistorySetDupeMode: - pHistoryInfo->GetDupInfo()->SetDupeMode(eMode); + historyInfo->GetDupInfo()->SetDupeMode(mode); break; case DownloadQueue::eaHistorySetDupeBackup: - error("Could not set duplicate parameter for %s: history item has wrong type", szNiceName); + error("Could not set duplicate parameter for %s: history item has wrong type", niceName); return; default: @@ -735,9 +735,9 @@ void HistoryCoordinator::HistorySetDupeParam(HistoryInfo* pHistoryInfo, Download } } -void HistoryCoordinator::Redownload(DownloadQueue* pDownloadQueue, HistoryInfo* pHistoryInfo) +void HistoryCoordinator::Redownload(DownloadQueue* downloadQueue, HistoryInfo* historyInfo) { - HistoryList::iterator it = std::find(pDownloadQueue->GetHistory()->begin(), - pDownloadQueue->GetHistory()->end(), pHistoryInfo); - HistoryRedownload(pDownloadQueue, it, pHistoryInfo, true); + HistoryList::iterator it = std::find(downloadQueue->GetHistory()->begin(), + downloadQueue->GetHistory()->end(), historyInfo); + HistoryRedownload(downloadQueue, it, historyInfo, true); } diff --git a/daemon/queue/HistoryCoordinator.h b/daemon/queue/HistoryCoordinator.h index ea216728..8cc155a9 100644 --- a/daemon/queue/HistoryCoordinator.h +++ b/daemon/queue/HistoryCoordinator.h @@ -32,16 +32,16 @@ class HistoryCoordinator : public Service { private: - void HistoryDelete(DownloadQueue* pDownloadQueue, HistoryList::iterator itHistory, HistoryInfo* pHistoryInfo, bool bFinal); - void HistoryReturn(DownloadQueue* pDownloadQueue, HistoryList::iterator itHistory, HistoryInfo* pHistoryInfo, bool bReprocess); - void HistoryRedownload(DownloadQueue* pDownloadQueue, HistoryList::iterator itHistory, HistoryInfo* pHistoryInfo, bool bRestorePauseState); - bool HistorySetParameter(HistoryInfo* pHistoryInfo, const char* szText); - void HistorySetDupeParam(HistoryInfo* pHistoryInfo, DownloadQueue::EEditAction eAction, const char* szText); - bool HistorySetCategory(HistoryInfo* pHistoryInfo, const char* szText); - bool HistorySetName(HistoryInfo* pHistoryInfo, const char* szText); - void HistoryTransformToDup(DownloadQueue* pDownloadQueue, HistoryInfo* pHistoryInfo, int rindex); - void SaveQueue(DownloadQueue* pDownloadQueue); - void PrepareEdit(DownloadQueue* pDownloadQueue, IDList* pIDList, DownloadQueue::EEditAction eAction); + void HistoryDelete(DownloadQueue* downloadQueue, HistoryList::iterator itHistory, HistoryInfo* historyInfo, bool final); + void HistoryReturn(DownloadQueue* downloadQueue, HistoryList::iterator itHistory, HistoryInfo* historyInfo, bool reprocess); + void HistoryRedownload(DownloadQueue* downloadQueue, HistoryList::iterator itHistory, HistoryInfo* historyInfo, bool restorePauseState); + bool HistorySetParameter(HistoryInfo* historyInfo, const char* text); + void HistorySetDupeParam(HistoryInfo* historyInfo, DownloadQueue::EEditAction action, const char* text); + bool HistorySetCategory(HistoryInfo* historyInfo, const char* text); + bool HistorySetName(HistoryInfo* historyInfo, const char* text); + void HistoryTransformToDup(DownloadQueue* downloadQueue, HistoryInfo* historyInfo, int rindex); + void SaveQueue(DownloadQueue* downloadQueue); + void PrepareEdit(DownloadQueue* downloadQueue, IDList* idList, DownloadQueue::EEditAction action); protected: virtual int ServiceInterval() { return 600000; } @@ -50,11 +50,11 @@ protected: public: HistoryCoordinator(); virtual ~HistoryCoordinator(); - void AddToHistory(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo); - bool EditList(DownloadQueue* pDownloadQueue, IDList* pIDList, DownloadQueue::EEditAction eAction, int iOffset, const char* szText); - void DeleteDiskFiles(NZBInfo* pNZBInfo); - void HistoryHide(DownloadQueue* pDownloadQueue, HistoryInfo* pHistoryInfo, int rindex); - void Redownload(DownloadQueue* pDownloadQueue, HistoryInfo* pHistoryInfo); + void AddToHistory(DownloadQueue* downloadQueue, NZBInfo* nzbInfo); + bool EditList(DownloadQueue* downloadQueue, IDList* idList, DownloadQueue::EEditAction action, int offset, const char* text); + void DeleteDiskFiles(NZBInfo* nzbInfo); + void HistoryHide(DownloadQueue* downloadQueue, HistoryInfo* historyInfo, int rindex); + void Redownload(DownloadQueue* downloadQueue, HistoryInfo* historyInfo); }; extern HistoryCoordinator* g_pHistoryCoordinator; diff --git a/daemon/queue/NZBFile.cpp b/daemon/queue/NZBFile.cpp index a9457c27..d704799a 100644 --- a/daemon/queue/NZBFile.cpp +++ b/daemon/queue/NZBFile.cpp @@ -54,23 +54,23 @@ using namespace MSXML; #include "DiskState.h" #include "Util.h" -NZBFile::NZBFile(const char* szFileName, const char* szCategory) +NZBFile::NZBFile(const char* fileName, const char* category) { debug("Creating NZBFile"); - m_szFileName = strdup(szFileName); - m_szPassword = NULL; - m_pNZBInfo = new NZBInfo(); - m_pNZBInfo->SetFilename(szFileName); - m_pNZBInfo->SetCategory(szCategory); - m_pNZBInfo->BuildDestDirName(); + m_fileName = strdup(fileName); + m_password = NULL; + m_nzbInfo = new NZBInfo(); + m_nzbInfo->SetFilename(fileName); + m_nzbInfo->SetCategory(category); + m_nzbInfo->BuildDestDirName(); #ifndef WIN32 - m_bPassword = false; - m_pFileInfo = NULL; - m_pArticle = NULL; - m_szTagContent = NULL; - m_iTagContentLen = 0; + m_hasPassword = false; + m_fileInfo = NULL; + m_article = NULL; + m_tagContent = NULL; + m_tagContentLen = 0; #endif } @@ -79,112 +79,112 @@ NZBFile::~NZBFile() debug("Destroying NZBFile"); // Cleanup - free(m_szFileName); - free(m_szPassword); + free(m_fileName); + free(m_password); #ifndef WIN32 - delete m_pFileInfo; - free(m_szTagContent); + delete m_fileInfo; + free(m_tagContent); #endif - delete m_pNZBInfo; + delete m_nzbInfo; } void NZBFile::LogDebugInfo() { - info(" NZBFile %s", m_szFileName); + info(" NZBFile %s", m_fileName); } -void NZBFile::AddArticle(FileInfo* pFileInfo, ArticleInfo* pArticleInfo) +void NZBFile::AddArticle(FileInfo* fileInfo, ArticleInfo* articleInfo) { // make Article-List big enough - while ((int)pFileInfo->GetArticles()->size() < pArticleInfo->GetPartNumber()) - pFileInfo->GetArticles()->push_back(NULL); + while ((int)fileInfo->GetArticles()->size() < articleInfo->GetPartNumber()) + fileInfo->GetArticles()->push_back(NULL); - int index = pArticleInfo->GetPartNumber() - 1; - if ((*pFileInfo->GetArticles())[index]) + int index = articleInfo->GetPartNumber() - 1; + if ((*fileInfo->GetArticles())[index]) { - delete (*pFileInfo->GetArticles())[index]; + delete (*fileInfo->GetArticles())[index]; } - (*pFileInfo->GetArticles())[index] = pArticleInfo; + (*fileInfo->GetArticles())[index] = articleInfo; } -void NZBFile::AddFileInfo(FileInfo* pFileInfo) +void NZBFile::AddFileInfo(FileInfo* fileInfo) { // calculate file size and delete empty articles - long long lSize = 0; - long long lMissedSize = 0; - long long lOneSize = 0; - int iUncountedArticles = 0; - int iMissedArticles = 0; - FileInfo::Articles* pArticles = pFileInfo->GetArticles(); - int iTotalArticles = (int)pArticles->size(); + long long size = 0; + long long missedSize = 0; + long long oneSize = 0; + int uncountedArticles = 0; + int missedArticles = 0; + FileInfo::Articles* articles = fileInfo->GetArticles(); + int totalArticles = (int)articles->size(); int i = 0; - for (FileInfo::Articles::iterator it = pArticles->begin(); it != pArticles->end(); ) + for (FileInfo::Articles::iterator it = articles->begin(); it != articles->end(); ) { - ArticleInfo* pArticle = *it; - if (!pArticle) + ArticleInfo* article = *it; + if (!article) { - pArticles->erase(it); - it = pArticles->begin() + i; - iMissedArticles++; - if (lOneSize > 0) + articles->erase(it); + it = articles->begin() + i; + missedArticles++; + if (oneSize > 0) { - lMissedSize += lOneSize; + missedSize += oneSize; } else { - iUncountedArticles++; + uncountedArticles++; } } else { - lSize += pArticle->GetSize(); - if (lOneSize == 0) + size += article->GetSize(); + if (oneSize == 0) { - lOneSize = pArticle->GetSize(); + oneSize = article->GetSize(); } it++; i++; } } - if (pArticles->empty()) + if (articles->empty()) { - delete pFileInfo; + delete fileInfo; return; } - lMissedSize += iUncountedArticles * lOneSize; - lSize += lMissedSize; - m_pNZBInfo->GetFileList()->push_back(pFileInfo); - pFileInfo->SetNZBInfo(m_pNZBInfo); - pFileInfo->SetSize(lSize); - pFileInfo->SetRemainingSize(lSize - lMissedSize); - pFileInfo->SetMissedSize(lMissedSize); - pFileInfo->SetTotalArticles(iTotalArticles); - pFileInfo->SetMissedArticles(iMissedArticles); + missedSize += uncountedArticles * oneSize; + size += missedSize; + m_nzbInfo->GetFileList()->push_back(fileInfo); + fileInfo->SetNZBInfo(m_nzbInfo); + fileInfo->SetSize(size); + fileInfo->SetRemainingSize(size - missedSize); + fileInfo->SetMissedSize(missedSize); + fileInfo->SetTotalArticles(totalArticles); + fileInfo->SetMissedArticles(missedArticles); } -void NZBFile::ParseSubject(FileInfo* pFileInfo, bool TryQuotes) +void NZBFile::ParseSubject(FileInfo* fileInfo, bool TryQuotes) { // Example subject: some garbage "title" yEnc (10/99) // strip the "yEnc (10/99)"-suffix - char szSubject[1024]; - strncpy(szSubject, pFileInfo->GetSubject(), sizeof(szSubject)); - szSubject[1024-1] = '\0'; - char* end = szSubject + strlen(szSubject) - 1; + char subject[1024]; + strncpy(subject, fileInfo->GetSubject(), sizeof(subject)); + subject[1024-1] = '\0'; + char* end = subject + strlen(subject) - 1; if (*end == ')') { end--; - while (strchr("0123456789", *end) && end > szSubject) end--; + while (strchr("0123456789", *end) && end > subject) end--; if (*end == '/') { end--; - while (strchr("0123456789", *end) && end > szSubject) end--; - if (end - 6 > szSubject && !strncmp(end - 6, " yEnc (", 7)) + while (strchr("0123456789", *end) && end > subject) end--; + if (end - 6 > subject && !strncmp(end - 6, " yEnc (", 7)) { end[-6] = '\0'; } @@ -194,7 +194,7 @@ void NZBFile::ParseSubject(FileInfo* pFileInfo, bool TryQuotes) if (TryQuotes) { // try to use the filename in quatation marks - char* p = szSubject; + char* p = subject; char* start = strchr(p, '\"'); if (start) { @@ -209,7 +209,7 @@ void NZBFile::ParseSubject(FileInfo* pFileInfo, bool TryQuotes) char* filename = (char*)malloc(len + 1); strncpy(filename, start, len); filename[len] = '\0'; - pFileInfo->SetFilename(filename); + fileInfo->SetFilename(filename); free(filename); return; } @@ -226,7 +226,7 @@ void NZBFile::ParseSubject(FileInfo* pFileInfo, bool TryQuotes) tokens.clear(); // tokenizing - char* p = szSubject; + char* p = subject; char* start = p; bool quot = false; while (true) @@ -285,7 +285,7 @@ void NZBFile::ParseSubject(FileInfo* pFileInfo, bool TryQuotes) break; } } - pFileInfo->SetFilename(besttoken); + fileInfo->SetFilename(besttoken); // free mem for (TokenList::iterator it = tokens.begin(); it != tokens.end(); it++) @@ -296,24 +296,24 @@ void NZBFile::ParseSubject(FileInfo* pFileInfo, bool TryQuotes) else { // subject is empty or contains only separators? - debug("Could not extract Filename from Subject: %s. Using Subject as Filename", pFileInfo->GetSubject()); - pFileInfo->SetFilename(pFileInfo->GetSubject()); + debug("Could not extract Filename from Subject: %s. Using Subject as Filename", fileInfo->GetSubject()); + fileInfo->SetFilename(fileInfo->GetSubject()); } } bool NZBFile::HasDuplicateFilenames() { - for (FileList::iterator it = m_pNZBInfo->GetFileList()->begin(); it != m_pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo1 = *it; - int iDupe = 1; - for (FileList::iterator it2 = it + 1; it2 != m_pNZBInfo->GetFileList()->end(); it2++) + FileInfo* fileInfo1 = *it; + int dupe = 1; + for (FileList::iterator it2 = it + 1; it2 != m_nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo2 = *it2; - if (!strcmp(pFileInfo1->GetFilename(), pFileInfo2->GetFilename()) && - strcmp(pFileInfo1->GetSubject(), pFileInfo2->GetSubject())) + FileInfo* fileInfo2 = *it2; + if (!strcmp(fileInfo1->GetFilename(), fileInfo2->GetFilename()) && + strcmp(fileInfo1->GetSubject(), fileInfo2->GetSubject())) { - iDupe++; + dupe++; } } @@ -323,7 +323,7 @@ bool NZBFile::HasDuplicateFilenames() // false "duplicate files"-alarm. // It's Ok for just two files to have the same filename, this is // an often case by posting-errors to repost bad files - if (iDupe > 2 || (iDupe == 2 && m_pNZBInfo->GetFileList()->size() == 2)) + if (dupe > 2 || (dupe == 2 && m_nzbInfo->GetFileList()->size() == 2)) { return true; } @@ -337,130 +337,130 @@ bool NZBFile::HasDuplicateFilenames() */ void NZBFile::BuildFilenames() { - for (FileList::iterator it = m_pNZBInfo->GetFileList()->begin(); it != m_pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - ParseSubject(pFileInfo, true); + FileInfo* fileInfo = *it; + ParseSubject(fileInfo, true); } if (HasDuplicateFilenames()) { - for (FileList::iterator it = m_pNZBInfo->GetFileList()->begin(); it != m_pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - ParseSubject(pFileInfo, false); + FileInfo* fileInfo = *it; + ParseSubject(fileInfo, false); } } if (HasDuplicateFilenames()) { - m_pNZBInfo->SetManyDupeFiles(true); - for (FileList::iterator it = m_pNZBInfo->GetFileList()->begin(); it != m_pNZBInfo->GetFileList()->end(); it++) + m_nzbInfo->SetManyDupeFiles(true); + for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - pFileInfo->SetFilename(pFileInfo->GetSubject()); + FileInfo* fileInfo = *it; + fileInfo->SetFilename(fileInfo->GetSubject()); } } } -bool CompareFileInfo(FileInfo* pFirst, FileInfo* pSecond) +bool CompareFileInfo(FileInfo* first, FileInfo* second) { - return strcmp(pFirst->GetFilename(), pSecond->GetFilename()) > 0; + return strcmp(first->GetFilename(), second->GetFilename()) > 0; } void NZBFile::CalcHashes() { TempFileList fileList; - for (FileList::iterator it = m_pNZBInfo->GetFileList()->begin(); it != m_pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { fileList.push_back(*it); } fileList.sort(CompareFileInfo); - unsigned int iFullContentHash = 0; - unsigned int iFilteredContentHash = 0; - int iUseForFilteredCount = 0; + unsigned int fullContentHash = 0; + unsigned int filteredContentHash = 0; + int useForFilteredCount = 0; for (TempFileList::iterator it = fileList.begin(); it != fileList.end(); it++) { - FileInfo* pFileInfo = *it; + FileInfo* fileInfo = *it; // check file extension - bool bSkip = !pFileInfo->GetParFile() && - Util::MatchFileExt(pFileInfo->GetFilename(), g_pOptions->GetExtCleanupDisk(), ",;"); + bool skip = !fileInfo->GetParFile() && + Util::MatchFileExt(fileInfo->GetFilename(), g_pOptions->GetExtCleanupDisk(), ",;"); - for (FileInfo::Articles::iterator it = pFileInfo->GetArticles()->begin(); it != pFileInfo->GetArticles()->end(); it++) + for (FileInfo::Articles::iterator it = fileInfo->GetArticles()->begin(); it != fileInfo->GetArticles()->end(); it++) { - ArticleInfo* pArticle = *it; - int iLen = strlen(pArticle->GetMessageID()); - iFullContentHash = Util::HashBJ96(pArticle->GetMessageID(), iLen, iFullContentHash); - if (!bSkip) + ArticleInfo* article = *it; + int len = strlen(article->GetMessageID()); + fullContentHash = Util::HashBJ96(article->GetMessageID(), len, fullContentHash); + if (!skip) { - iFilteredContentHash = Util::HashBJ96(pArticle->GetMessageID(), iLen, iFilteredContentHash); - iUseForFilteredCount++; + filteredContentHash = Util::HashBJ96(article->GetMessageID(), len, filteredContentHash); + useForFilteredCount++; } } } // if filtered hash is based on less than a half of files - do not use filtered hash at all - if (iUseForFilteredCount < (int)fileList.size() / 2) + if (useForFilteredCount < (int)fileList.size() / 2) { - iFilteredContentHash = 0; + filteredContentHash = 0; } - m_pNZBInfo->SetFullContentHash(iFullContentHash); - m_pNZBInfo->SetFilteredContentHash(iFilteredContentHash); + m_nzbInfo->SetFullContentHash(fullContentHash); + m_nzbInfo->SetFilteredContentHash(filteredContentHash); } void NZBFile::ProcessFiles() { BuildFilenames(); - for (FileList::iterator it = m_pNZBInfo->GetFileList()->begin(); it != m_pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - pFileInfo->MakeValidFilename(); + FileInfo* fileInfo = *it; + fileInfo->MakeValidFilename(); - char szLoFileName[1024]; - strncpy(szLoFileName, pFileInfo->GetFilename(), 1024); - szLoFileName[1024-1] = '\0'; - for (char* p = szLoFileName; *p; p++) *p = tolower(*p); // convert string to lowercase - bool bParFile = strstr(szLoFileName, ".par2"); + char loFileName[1024]; + strncpy(loFileName, fileInfo->GetFilename(), 1024); + loFileName[1024-1] = '\0'; + for (char* p = loFileName; *p; p++) *p = tolower(*p); // convert string to lowercase + bool parFile = strstr(loFileName, ".par2"); - m_pNZBInfo->SetFileCount(m_pNZBInfo->GetFileCount() + 1); - m_pNZBInfo->SetTotalArticles(m_pNZBInfo->GetTotalArticles() + pFileInfo->GetTotalArticles()); - m_pNZBInfo->SetSize(m_pNZBInfo->GetSize() + pFileInfo->GetSize()); - m_pNZBInfo->SetRemainingSize(m_pNZBInfo->GetRemainingSize() + pFileInfo->GetRemainingSize()); - m_pNZBInfo->SetFailedSize(m_pNZBInfo->GetFailedSize() + pFileInfo->GetMissedSize()); - m_pNZBInfo->SetCurrentFailedSize(m_pNZBInfo->GetFailedSize()); + m_nzbInfo->SetFileCount(m_nzbInfo->GetFileCount() + 1); + m_nzbInfo->SetTotalArticles(m_nzbInfo->GetTotalArticles() + fileInfo->GetTotalArticles()); + m_nzbInfo->SetSize(m_nzbInfo->GetSize() + fileInfo->GetSize()); + m_nzbInfo->SetRemainingSize(m_nzbInfo->GetRemainingSize() + fileInfo->GetRemainingSize()); + m_nzbInfo->SetFailedSize(m_nzbInfo->GetFailedSize() + fileInfo->GetMissedSize()); + m_nzbInfo->SetCurrentFailedSize(m_nzbInfo->GetFailedSize()); - pFileInfo->SetParFile(bParFile); - if (bParFile) + fileInfo->SetParFile(parFile); + if (parFile) { - m_pNZBInfo->SetParSize(m_pNZBInfo->GetParSize() + pFileInfo->GetSize()); - m_pNZBInfo->SetParFailedSize(m_pNZBInfo->GetParFailedSize() + pFileInfo->GetMissedSize()); - m_pNZBInfo->SetParCurrentFailedSize(m_pNZBInfo->GetParFailedSize()); - m_pNZBInfo->SetRemainingParCount(m_pNZBInfo->GetRemainingParCount() + 1); + m_nzbInfo->SetParSize(m_nzbInfo->GetParSize() + fileInfo->GetSize()); + m_nzbInfo->SetParFailedSize(m_nzbInfo->GetParFailedSize() + fileInfo->GetMissedSize()); + m_nzbInfo->SetParCurrentFailedSize(m_nzbInfo->GetParFailedSize()); + m_nzbInfo->SetRemainingParCount(m_nzbInfo->GetRemainingParCount() + 1); } } - m_pNZBInfo->UpdateMinMaxTime(); + m_nzbInfo->UpdateMinMaxTime(); CalcHashes(); if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) { - for (FileList::iterator it = m_pNZBInfo->GetFileList()->begin(); it != m_pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - g_pDiskState->SaveFile(pFileInfo); - pFileInfo->ClearArticles(); + FileInfo* fileInfo = *it; + g_pDiskState->SaveFile(fileInfo); + fileInfo->ClearArticles(); } } - if (m_szPassword) + if (m_password) { ReadPassword(); } @@ -472,42 +472,42 @@ void NZBFile::ProcessFiles() */ void NZBFile::ReadPassword() { - FILE* pFile = fopen(m_szFileName, FOPEN_RB); - if (!pFile) + FILE* file = fopen(m_fileName, FOPEN_RB); + if (!file) { return; } // obtain file size. - fseek(pFile , 0 , SEEK_END); - int iSize = (int)ftell(pFile); - rewind(pFile); + fseek(file , 0 , SEEK_END); + int size = (int)ftell(file); + rewind(file); // reading first 4KB of the file // allocate memory to contain the whole file. char* buf = (char*)malloc(4096); - iSize = iSize < 4096 ? iSize : 4096; + size = size < 4096 ? size : 4096; // copy the file into the buffer. - fread(buf, 1, iSize, pFile); + fread(buf, 1, size, file); - fclose(pFile); + fclose(file); - buf[iSize-1] = '\0'; + buf[size-1] = '\0'; - char* szMetaPassword = strstr(buf, ""); - if (szMetaPassword) + char* metaPassword = strstr(buf, ""); + if (metaPassword) { - szMetaPassword += 22; // length of '' - char* szEnd = strstr(szMetaPassword, ""); - if (szEnd) + metaPassword += 22; // length of '' + char* end = strstr(metaPassword, ""); + if (end) { - *szEnd = '\0'; - WebUtil::XmlDecode(szMetaPassword); - free(m_szPassword); - m_szPassword = strdup(szMetaPassword); + *end = '\0'; + WebUtil::XmlDecode(metaPassword); + free(m_password); + m_password = strdup(metaPassword); } } @@ -533,17 +533,17 @@ bool NZBFile::Parse() doc->put_validateOnParse(VARIANT_FALSE); doc->put_async(VARIANT_FALSE); - _variant_t vFilename(m_szFileName); + _variant_t vFilename(m_fileName); // 1. first trying to load via filename without URL-encoding (certain charaters doesn't work when encoded) VARIANT_BOOL success = doc->load(vFilename); if (success == VARIANT_FALSE) { // 2. now trying filename encoded as URL - char szURL[2048]; - EncodeURL(m_szFileName, szURL, 2048); - debug("url=\"%s\"", szURL); - _variant_t vURL(szURL); + char url[2048]; + EncodeURL(m_fileName, url, 2048); + debug("url=\"%s\"", url); + _variant_t vURL(url); success = doc->load(vURL); } @@ -551,12 +551,12 @@ bool NZBFile::Parse() if (success == VARIANT_FALSE) { _bstr_t r(doc->GetparseError()->reason); - const char* szErrMsg = r; + const char* errMsg = r; - char szMessageText[1024]; - snprintf(szMessageText, 1024, "Error parsing nzb-file %s: %s", Util::BaseFileName(m_szFileName), szErrMsg); - szMessageText[1024-1] = '\0'; - m_pNZBInfo->AddMessage(Message::mkError, szMessageText); + char messageText[1024]; + snprintf(messageText, 1024, "Error parsing nzb-file %s: %s", Util::BaseFileName(m_fileName), errMsg); + messageText[1024-1] = '\0'; + m_nzbInfo->AddMessage(Message::mkError, messageText); return false; } @@ -568,10 +568,10 @@ bool NZBFile::Parse() if (GetNZBInfo()->GetFileList()->empty()) { - char szMessageText[1024]; - snprintf(szMessageText, 1024, "Error parsing nzb-file %s: file has no content", Util::BaseFileName(m_szFileName)); - szMessageText[1024-1] = '\0'; - m_pNZBInfo->AddMessage(Message::mkError, szMessageText); + char messageText[1024]; + snprintf(messageText, 1024, "Error parsing nzb-file %s: file has no content", Util::BaseFileName(m_fileName)); + messageText[1024-1] = '\0'; + m_nzbInfo->AddMessage(Message::mkError, messageText); return false; } @@ -581,15 +581,15 @@ bool NZBFile::Parse() return true; } -void NZBFile::EncodeURL(const char* szFilename, char* szURL, int iBufLen) +void NZBFile::EncodeURL(const char* filename, char* url, int bufLen) { - char szUtfFilename[2048]; - strncpy(szUtfFilename, szFilename, 2048); - szUtfFilename[2048-1] = '\0'; - WebUtil::AnsiToUtf8(szUtfFilename, 2048); + char utfFilename[2048]; + strncpy(utfFilename, filename, 2048); + utfFilename[2048-1] = '\0'; + WebUtil::AnsiToUtf8(utfFilename, 2048); - char* szEnd = szURL + iBufLen; - for (char* p = szUtfFilename; *p && szURL < szEnd - 3; p++) + char* end = url + bufLen; + for (char* p = utfFilename; *p && url < end - 3; p++) { char ch = *p; if (('0' <= ch && ch <= '9') || @@ -597,18 +597,18 @@ void NZBFile::EncodeURL(const char* szFilename, char* szURL, int iBufLen) ('A' <= ch && ch <= 'Z') || ch == '-' || ch == '.' || ch == '_' || ch == '~') { - *szURL++ = ch; + *url++ = ch; } else { - *szURL++ = '%'; + *url++ = '%'; int a = (unsigned char)ch >> 4; - *szURL++ = a > 9 ? a - 10 + 'A' : a + '0'; + *url++ = a > 9 ? a - 10 + 'A' : a + '0'; a = ch & 0xF; - *szURL++ = a > 9 ? a - 10 + 'A' : a + '0'; + *url++ = a > 9 ? a - 10 + 'A' : a + '0'; } } - *szURL = NULL; + *url = NULL; } bool NZBFile::ParseNZB(IUnknown* nzb) @@ -620,7 +620,7 @@ bool NZBFile::ParseNZB(IUnknown* nzb) if (node) { _bstr_t password(node->Gettext()); - m_szPassword = strdup(password); + m_password = strdup(password); } MSXML::IXMLDOMNodeListPtr fileList = root->selectNodes("/nzb/file"); @@ -630,14 +630,14 @@ bool NZBFile::ParseNZB(IUnknown* nzb) MSXML::IXMLDOMNodePtr attribute = node->Getattributes()->getNamedItem("subject"); if (!attribute) return false; _bstr_t subject(attribute->Gettext()); - FileInfo* pFileInfo = new FileInfo(); - pFileInfo->SetSubject(subject); + FileInfo* fileInfo = new FileInfo(); + fileInfo->SetSubject(subject); attribute = node->Getattributes()->getNamedItem("date"); if (attribute) { _bstr_t date(attribute->Gettext()); - pFileInfo->SetTime(atoi(date)); + fileInfo->SetTime(atoi(date)); } MSXML::IXMLDOMNodeListPtr groupList = node->selectNodes("groups/group"); @@ -645,16 +645,16 @@ bool NZBFile::ParseNZB(IUnknown* nzb) { MSXML::IXMLDOMNodePtr node = groupList->Getitem(g); _bstr_t group = node->Gettext(); - pFileInfo->GetGroups()->push_back(strdup((const char*)group)); + fileInfo->GetGroups()->push_back(strdup((const char*)group)); } MSXML::IXMLDOMNodeListPtr segmentList = node->selectNodes("segments/segment"); for (int g = 0; g < segmentList->Getlength(); g++) { MSXML::IXMLDOMNodePtr node = segmentList->Getitem(g); - _bstr_t id = node->Gettext(); - char szId[2048]; - snprintf(szId, 2048, "<%s>", (const char*)id); + _bstr_t bid = node->Gettext(); + char id[2048]; + snprintf(id, 2048, "<%s>", (const char*)bid); MSXML::IXMLDOMNodePtr attribute = node->Getattributes()->getNamedItem("number"); if (!attribute) return false; @@ -669,15 +669,15 @@ bool NZBFile::ParseNZB(IUnknown* nzb) if (partNumber > 0) { - ArticleInfo* pArticle = new ArticleInfo(); - pArticle->SetPartNumber(partNumber); - pArticle->SetMessageID(szId); - pArticle->SetSize(lsize); - AddArticle(pFileInfo, pArticle); + ArticleInfo* article = new ArticleInfo(); + article->SetPartNumber(partNumber); + article->SetMessageID(id); + article->SetSize(lsize); + AddArticle(fileInfo, article); } } - AddFileInfo(pFileInfo); + AddFileInfo(fileInfo); } return true; } @@ -693,25 +693,25 @@ bool NZBFile::Parse() SAX_handler.error = reinterpret_cast(SAX_error); SAX_handler.getEntity = reinterpret_cast(SAX_getEntity); - m_bIgnoreNextError = false; + m_ignoreNextError = false; - int ret = xmlSAXUserParseFile(&SAX_handler, this, m_szFileName); + int ret = xmlSAXUserParseFile(&SAX_handler, this, m_fileName); if (ret != 0) { - char szMessageText[1024]; - snprintf(szMessageText, 1024, "Error parsing nzb-file %s", Util::BaseFileName(m_szFileName)); - szMessageText[1024-1] = '\0'; - m_pNZBInfo->AddMessage(Message::mkError, szMessageText); + char messageText[1024]; + snprintf(messageText, 1024, "Error parsing nzb-file %s", Util::BaseFileName(m_fileName)); + messageText[1024-1] = '\0'; + m_nzbInfo->AddMessage(Message::mkError, messageText); return false; } - if (m_pNZBInfo->GetFileList()->empty()) + if (m_nzbInfo->GetFileList()->empty()) { - char szMessageText[1024]; - snprintf(szMessageText, 1024, "Error parsing nzb-file %s: file has no content", Util::BaseFileName(m_szFileName)); - szMessageText[1024-1] = '\0'; - m_pNZBInfo->AddMessage(Message::mkError, szMessageText); + char messageText[1024]; + snprintf(messageText, 1024, "Error parsing nzb-file %s: file has no content", Util::BaseFileName(m_fileName)); + messageText[1024-1] = '\0'; + m_nzbInfo->AddMessage(Message::mkError, messageText); return false; } @@ -722,25 +722,25 @@ bool NZBFile::Parse() void NZBFile::Parse_StartElement(const char *name, const char **atts) { - char szTagAttrMessage[1024]; - snprintf(szTagAttrMessage, 1024, "Malformed nzb-file, tag <%s> must have attributes", name); - szTagAttrMessage[1024-1] = '\0'; + char tagAttrMessage[1024]; + snprintf(tagAttrMessage, 1024, "Malformed nzb-file, tag <%s> must have attributes", name); + tagAttrMessage[1024-1] = '\0'; - if (m_szTagContent) + if (m_tagContent) { - free(m_szTagContent); - m_szTagContent = NULL; - m_iTagContentLen = 0; + free(m_tagContent); + m_tagContent = NULL; + m_tagContentLen = 0; } if (!strcmp("file", name)) { - m_pFileInfo = new FileInfo(); - m_pFileInfo->SetFilename(m_szFileName); + m_fileInfo = new FileInfo(); + m_fileInfo->SetFilename(m_fileName); if (!atts) { - m_pNZBInfo->AddMessage(Message::mkWarning, szTagAttrMessage); + m_nzbInfo->AddMessage(Message::mkWarning, tagAttrMessage); return; } @@ -750,25 +750,25 @@ void NZBFile::Parse_StartElement(const char *name, const char **atts) const char* attrvalue = atts[i + 1]; if (!strcmp("subject", attrname)) { - m_pFileInfo->SetSubject(attrvalue); + m_fileInfo->SetSubject(attrvalue); } if (!strcmp("date", attrname)) { - m_pFileInfo->SetTime(atoi(attrvalue)); + m_fileInfo->SetTime(atoi(attrvalue)); } } } else if (!strcmp("segment", name)) { - if (!m_pFileInfo) + if (!m_fileInfo) { - m_pNZBInfo->AddMessage(Message::mkWarning, "Malformed nzb-file, tag without tag "); + m_nzbInfo->AddMessage(Message::mkWarning, "Malformed nzb-file, tag without tag "); return; } if (!atts) { - m_pNZBInfo->AddMessage(Message::mkWarning, szTagAttrMessage); + m_nzbInfo->AddMessage(Message::mkWarning, tagAttrMessage); return; } @@ -792,20 +792,20 @@ void NZBFile::Parse_StartElement(const char *name, const char **atts) if (partNumber > 0) { // new segment, add it! - m_pArticle = new ArticleInfo(); - m_pArticle->SetPartNumber(partNumber); - m_pArticle->SetSize(lsize); - AddArticle(m_pFileInfo, m_pArticle); + m_article = new ArticleInfo(); + m_article->SetPartNumber(partNumber); + m_article->SetSize(lsize); + AddArticle(m_fileInfo, m_article); } } else if (!strcmp("meta", name)) { if (!atts) { - m_pNZBInfo->AddMessage(Message::mkWarning, szTagAttrMessage); + m_nzbInfo->AddMessage(Message::mkWarning, tagAttrMessage); return; } - m_bPassword = atts[0] && atts[1] && !strcmp("type", atts[0]) && !strcmp("password", atts[1]); + m_hasPassword = atts[0] && atts[1] && !strcmp("type", atts[0]) && !strcmp("password", atts[1]); } } @@ -814,25 +814,25 @@ void NZBFile::Parse_EndElement(const char *name) if (!strcmp("file", name)) { // Close the file element, add the new file to file-list - AddFileInfo(m_pFileInfo); - m_pFileInfo = NULL; - m_pArticle = NULL; + AddFileInfo(m_fileInfo); + m_fileInfo = NULL; + m_article = NULL; } else if (!strcmp("group", name)) { - if (!m_pFileInfo) + if (!m_fileInfo) { // error: bad nzb-file return; } - m_pFileInfo->GetGroups()->push_back(m_szTagContent); - m_szTagContent = NULL; - m_iTagContentLen = 0; + m_fileInfo->GetGroups()->push_back(m_tagContent); + m_tagContent = NULL; + m_tagContentLen = 0; } else if (!strcmp("segment", name)) { - if (!m_pFileInfo || !m_pArticle) + if (!m_fileInfo || !m_article) { // error: bad nzb-file return; @@ -840,35 +840,35 @@ void NZBFile::Parse_EndElement(const char *name) // Get the #text part char ID[2048]; - snprintf(ID, 2048, "<%s>", m_szTagContent); - m_pArticle->SetMessageID(ID); - m_pArticle = NULL; + snprintf(ID, 2048, "<%s>", m_tagContent); + m_article->SetMessageID(ID); + m_article = NULL; } - else if (!strcmp("meta", name) && m_bPassword) + else if (!strcmp("meta", name) && m_hasPassword) { - m_szPassword = strdup(m_szTagContent); + m_password = strdup(m_tagContent); } } void NZBFile::Parse_Content(const char *buf, int len) { - m_szTagContent = (char*)realloc(m_szTagContent, m_iTagContentLen + len + 1); - strncpy(m_szTagContent + m_iTagContentLen, buf, len); - m_iTagContentLen += len; - m_szTagContent[m_iTagContentLen] = '\0'; + m_tagContent = (char*)realloc(m_tagContent, m_tagContentLen + len + 1); + strncpy(m_tagContent + m_tagContentLen, buf, len); + m_tagContentLen += len; + m_tagContent[m_tagContentLen] = '\0'; } -void NZBFile::SAX_StartElement(NZBFile* pFile, const char *name, const char **atts) +void NZBFile::SAX_StartElement(NZBFile* file, const char *name, const char **atts) { - pFile->Parse_StartElement(name, atts); + file->Parse_StartElement(name, atts); } -void NZBFile::SAX_EndElement(NZBFile* pFile, const char *name) +void NZBFile::SAX_EndElement(NZBFile* file, const char *name) { - pFile->Parse_EndElement(name); + file->Parse_EndElement(name); } -void NZBFile::SAX_characters(NZBFile* pFile, const char * xmlstr, int len) +void NZBFile::SAX_characters(NZBFile* file, const char * xmlstr, int len) { char* str = (char*)xmlstr; @@ -906,43 +906,43 @@ void NZBFile::SAX_characters(NZBFile* pFile, const char * xmlstr, int len) if (newlen > 0) { // interpret tag content - pFile->Parse_Content(str + off, newlen); + file->Parse_Content(str + off, newlen); } } -void* NZBFile::SAX_getEntity(NZBFile* pFile, const char * name) +void* NZBFile::SAX_getEntity(NZBFile* file, const char * name) { xmlEntityPtr e = xmlGetPredefinedEntity((xmlChar* )name); if (!e) { - pFile->GetNZBInfo()->AddMessage(Message::mkWarning, "entity not found"); - pFile->m_bIgnoreNextError = true; + file->GetNZBInfo()->AddMessage(Message::mkWarning, "entity not found"); + file->m_ignoreNextError = true; } return e; } -void NZBFile::SAX_error(NZBFile* pFile, const char *msg, ...) +void NZBFile::SAX_error(NZBFile* file, const char *msg, ...) { - if (pFile->m_bIgnoreNextError) + if (file->m_ignoreNextError) { - pFile->m_bIgnoreNextError = false; + file->m_ignoreNextError = false; return; } va_list argp; va_start(argp, msg); - char szErrMsg[1024]; - vsnprintf(szErrMsg, sizeof(szErrMsg), msg, argp); - szErrMsg[1024-1] = '\0'; + char errMsg[1024]; + vsnprintf(errMsg, sizeof(errMsg), msg, argp); + errMsg[1024-1] = '\0'; va_end(argp); // remove trailing CRLF - for (char* pend = szErrMsg + strlen(szErrMsg) - 1; pend >= szErrMsg && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; + for (char* pend = errMsg + strlen(errMsg) - 1; pend >= errMsg && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; - char szTextMessage[1024]; - snprintf(szTextMessage, 1024, "Error parsing nzb-file: %s", szErrMsg); - szTextMessage[1024-1] = '\0'; - pFile->GetNZBInfo()->AddMessage(Message::mkError, szTextMessage); + char textMessage[1024]; + snprintf(textMessage, 1024, "Error parsing nzb-file: %s", errMsg); + textMessage[1024-1] = '\0'; + file->GetNZBInfo()->AddMessage(Message::mkError, textMessage); } #endif diff --git a/daemon/queue/NZBFile.h b/daemon/queue/NZBFile.h index c7e8d9a0..a3619283 100644 --- a/daemon/queue/NZBFile.h +++ b/daemon/queue/NZBFile.h @@ -37,13 +37,13 @@ public: typedef std::list TempFileList; private: - NZBInfo* m_pNZBInfo; - char* m_szFileName; - char* m_szPassword; + NZBInfo* m_nzbInfo; + char* m_fileName; + char* m_password; - void AddArticle(FileInfo* pFileInfo, ArticleInfo* pArticleInfo); - void AddFileInfo(FileInfo* pFileInfo); - void ParseSubject(FileInfo* pFileInfo, bool TryQuotes); + void AddArticle(FileInfo* fileInfo, ArticleInfo* articleInfo); + void AddFileInfo(FileInfo* fileInfo); + void ParseSubject(FileInfo* fileInfo, bool TryQuotes); void BuildFilenames(); void ProcessFiles(); void CalcHashes(); @@ -51,33 +51,33 @@ private: void ReadPassword(); #ifdef WIN32 bool ParseNZB(IUnknown* nzb); - static void EncodeURL(const char* szFilename, char* szURL, int iBufLen); + static void EncodeURL(const char* filename, char* url, int bufLen); #else - FileInfo* m_pFileInfo; - ArticleInfo* m_pArticle; - char* m_szTagContent; - int m_iTagContentLen; - bool m_bIgnoreNextError; - bool m_bPassword; + FileInfo* m_fileInfo; + ArticleInfo* m_article; + char* m_tagContent; + int m_tagContentLen; + bool m_ignoreNextError; + bool m_hasPassword; - static void SAX_StartElement(NZBFile* pFile, const char *name, const char **atts); - static void SAX_EndElement(NZBFile* pFile, const char *name); - static void SAX_characters(NZBFile* pFile, const char * xmlstr, int len); - static void* SAX_getEntity(NZBFile* pFile, const char * name); - static void SAX_error(NZBFile* pFile, const char *msg, ...); + static void SAX_StartElement(NZBFile* file, const char *name, const char **atts); + static void SAX_EndElement(NZBFile* file, const char *name); + static void SAX_characters(NZBFile* file, const char * xmlstr, int len); + static void* SAX_getEntity(NZBFile* file, const char * name); + static void SAX_error(NZBFile* file, const char *msg, ...); void Parse_StartElement(const char *name, const char **atts); void Parse_EndElement(const char *name); void Parse_Content(const char *buf, int len); #endif public: - NZBFile(const char* szFileName, const char* szCategory); + NZBFile(const char* fileName, const char* category); ~NZBFile(); bool Parse(); - const char* GetFileName() const { return m_szFileName; } - NZBInfo* GetNZBInfo() { return m_pNZBInfo; } - const char* GetPassword() { return m_szPassword; } - void DetachNZBInfo() { m_pNZBInfo = NULL; } + const char* GetFileName() const { return m_fileName; } + NZBInfo* GetNZBInfo() { return m_nzbInfo; } + const char* GetPassword() { return m_password; } + void DetachNZBInfo() { m_nzbInfo = NULL; } void LogDebugInfo(); }; diff --git a/daemon/queue/QueueCoordinator.cpp b/daemon/queue/QueueCoordinator.cpp index c237251c..a5b6333e 100644 --- a/daemon/queue/QueueCoordinator.cpp +++ b/daemon/queue/QueueCoordinator.cpp @@ -54,29 +54,29 @@ #include "StatMeter.h" bool QueueCoordinator::CoordinatorDownloadQueue::EditEntry( - int ID, EEditAction eAction, int iOffset, const char* szText) + int ID, EEditAction action, int offset, const char* text) { - return m_pOwner->m_QueueEditor.EditEntry(&m_pOwner->m_DownloadQueue, ID, eAction, iOffset, szText); + return m_owner->m_queueEditor.EditEntry(&m_owner->m_downloadQueue, ID, action, offset, text); } bool QueueCoordinator::CoordinatorDownloadQueue::EditList( - IDList* pIDList, NameList* pNameList, EMatchMode eMatchMode, EEditAction eAction, int iOffset, const char* szText) + IDList* idList, NameList* nameList, EMatchMode matchMode, EEditAction action, int offset, const char* text) { - m_bMassEdit = true; - bool bRet = m_pOwner->m_QueueEditor.EditList(&m_pOwner->m_DownloadQueue, pIDList, pNameList, eMatchMode, eAction, iOffset, szText); - m_bMassEdit = false; - if (m_bWantSave) + m_massEdit = true; + bool ret = m_owner->m_queueEditor.EditList(&m_owner->m_downloadQueue, idList, nameList, matchMode, action, offset, text); + m_massEdit = false; + if (m_wantSave) { Save(); } - return bRet; + return ret; } void QueueCoordinator::CoordinatorDownloadQueue::Save() { - if (m_bMassEdit) + if (m_massEdit) { - m_bWantSave = true; + m_wantSave = true; return; } @@ -85,20 +85,20 @@ void QueueCoordinator::CoordinatorDownloadQueue::Save() g_pDiskState->SaveDownloadQueue(this); } - m_bWantSave = false; + m_wantSave = false; } QueueCoordinator::QueueCoordinator() { debug("Creating QueueCoordinator"); - m_bHasMoreJobs = true; - m_iServerConfigGeneration = 0; + m_hasMoreJobs = true; + m_serverConfigGeneration = 0; g_pLog->RegisterDebuggable(this); - m_DownloadQueue.m_pOwner = this; - CoordinatorDownloadQueue::Init(&m_DownloadQueue); + m_downloadQueue.m_owner = this; + CoordinatorDownloadQueue::Init(&m_downloadQueue); } QueueCoordinator::~QueueCoordinator() @@ -109,11 +109,11 @@ QueueCoordinator::~QueueCoordinator() g_pLog->UnregisterDebuggable(this); debug("Deleting ArticleDownloaders"); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { delete *it; } - m_ActiveDownloads.clear(); + m_activeDownloads.clear(); CoordinatorDownloadQueue::Final(); @@ -122,19 +122,19 @@ QueueCoordinator::~QueueCoordinator() void QueueCoordinator::Load() { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - bool bStatLoaded = true; - bool bPerfectServerMatch = true; - bool bQueueLoaded = false; + bool statLoaded = true; + bool perfectServerMatch = true; + bool queueLoaded = false; if (g_pOptions->GetServerMode() && g_pOptions->GetSaveQueue()) { - bStatLoaded = g_pStatMeter->Load(&bPerfectServerMatch); + statLoaded = g_pStatMeter->Load(&perfectServerMatch); if (g_pOptions->GetReloadQueue() && g_pDiskState->DownloadQueueExists()) { - bQueueLoaded = g_pDiskState->LoadDownloadQueue(pDownloadQueue, g_pServerPool->GetServers()); + queueLoaded = g_pDiskState->LoadDownloadQueue(downloadQueue, g_pServerPool->GetServers()); } else { @@ -142,12 +142,12 @@ void QueueCoordinator::Load() } } - if (bQueueLoaded && bStatLoaded) + if (queueLoaded && statLoaded) { - g_pDiskState->CleanupTempDir(pDownloadQueue); + g_pDiskState->CleanupTempDir(downloadQueue); } - if (bQueueLoaded && bStatLoaded && !bPerfectServerMatch) + if (queueLoaded && statLoaded && !perfectServerMatch) { debug("Changes in section of config file detected, resaving queue"); @@ -155,38 +155,38 @@ void QueueCoordinator::Load() g_pStatMeter->Save(); // re-save queue into diskstate to update server ids - pDownloadQueue->Save(); + downloadQueue->Save(); // re-save file states into diskstate to update server ids if (g_pOptions->GetServerMode() && g_pOptions->GetSaveQueue()) { - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; + NZBInfo* nzbInfo = *it; if (g_pOptions->GetContinuePartial()) { - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - if (!pFileInfo->GetArticles()->empty()) + FileInfo* fileInfo = *it2; + if (!fileInfo->GetArticles()->empty()) { - g_pDiskState->SaveFileState(pFileInfo, false); + g_pDiskState->SaveFileState(fileInfo, false); } } } - for (CompletedFiles::iterator it2 = pNZBInfo->GetCompletedFiles()->begin(); it2 != pNZBInfo->GetCompletedFiles()->end(); it2++) + for (CompletedFiles::iterator it2 = nzbInfo->GetCompletedFiles()->begin(); it2 != nzbInfo->GetCompletedFiles()->end(); it2++) { - CompletedFile* pCompletedFile = *it2; - if (pCompletedFile->GetStatus() != CompletedFile::cfSuccess && pCompletedFile->GetID() > 0) + CompletedFile* completedFile = *it2; + if (completedFile->GetStatus() != CompletedFile::cfSuccess && completedFile->GetID() > 0) { - FileInfo* pFileInfo = new FileInfo(pCompletedFile->GetID()); - if (g_pDiskState->LoadFileState(pFileInfo, g_pServerPool->GetServers(), false)) + FileInfo* fileInfo = new FileInfo(completedFile->GetID()); + if (g_pDiskState->LoadFileState(fileInfo, g_pServerPool->GetServers(), false)) { - g_pDiskState->SaveFileState(pFileInfo, true); + g_pDiskState->SaveFileState(fileInfo, true); } - delete pFileInfo; + delete fileInfo; } } } @@ -203,87 +203,87 @@ void QueueCoordinator::Run() Load(); AdjustDownloadsLimit(); - bool bWasStandBy = true; - bool bArticeDownloadsRunning = false; - int iResetCounter = 0; + bool wasStandBy = true; + bool articeDownloadsRunning = false; + int resetCounter = 0; g_pStatMeter->IntervalCheck(); while (!IsStopped()) { - bool bDownloadsChecked = false; - bool bDownloadStarted = false; - NNTPConnection* pConnection = g_pServerPool->GetConnection(0, NULL, NULL); - if (pConnection) + bool downloadsChecked = false; + bool downloadStarted = false; + NNTPConnection* connection = g_pServerPool->GetConnection(0, NULL, NULL); + if (connection) { // start download for next article - FileInfo* pFileInfo; - ArticleInfo* pArticleInfo; - bool bFreeConnection = false; + FileInfo* fileInfo; + ArticleInfo* articleInfo; + bool freeConnection = false; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - bool bHasMoreArticles = GetNextArticle(pDownloadQueue, pFileInfo, pArticleInfo); - bArticeDownloadsRunning = !m_ActiveDownloads.empty(); - bDownloadsChecked = true; - m_bHasMoreJobs = bHasMoreArticles || bArticeDownloadsRunning; - if (bHasMoreArticles && !IsStopped() && (int)m_ActiveDownloads.size() < m_iDownloadsLimit && - (!g_pOptions->GetTempPauseDownload() || pFileInfo->GetExtraPriority())) + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + bool hasMoreArticles = GetNextArticle(downloadQueue, fileInfo, articleInfo); + articeDownloadsRunning = !m_activeDownloads.empty(); + downloadsChecked = true; + m_hasMoreJobs = hasMoreArticles || articeDownloadsRunning; + if (hasMoreArticles && !IsStopped() && (int)m_activeDownloads.size() < m_downloadsLimit && + (!g_pOptions->GetTempPauseDownload() || fileInfo->GetExtraPriority())) { - StartArticleDownload(pFileInfo, pArticleInfo, pConnection); - bArticeDownloadsRunning = true; - bDownloadStarted = true; + StartArticleDownload(fileInfo, articleInfo, connection); + articeDownloadsRunning = true; + downloadStarted = true; } else { - bFreeConnection = true; + freeConnection = true; } DownloadQueue::Unlock(); - if (bFreeConnection) + if (freeConnection) { - g_pServerPool->FreeConnection(pConnection, false); + g_pServerPool->FreeConnection(connection, false); } } - if (!bDownloadsChecked) + if (!downloadsChecked) { DownloadQueue::Lock(); - bArticeDownloadsRunning = !m_ActiveDownloads.empty(); + articeDownloadsRunning = !m_activeDownloads.empty(); DownloadQueue::Unlock(); } - bool bStandBy = !bArticeDownloadsRunning; - if (bStandBy != bWasStandBy) + bool standBy = !articeDownloadsRunning; + if (standBy != wasStandBy) { - g_pStatMeter->EnterLeaveStandBy(bStandBy); - bWasStandBy = bStandBy; - if (bStandBy) + g_pStatMeter->EnterLeaveStandBy(standBy); + wasStandBy = standBy; + if (standBy) { SavePartialState(); } } // sleep longer in StandBy - int iSleepInterval = bDownloadStarted ? 0 : bStandBy ? 100 : 5; - usleep(iSleepInterval * 1000); + int sleepInterval = downloadStarted ? 0 : standBy ? 100 : 5; + usleep(sleepInterval * 1000); - if (!bStandBy) + if (!standBy) { g_pStatMeter->AddSpeedReading(0); } - Util::SetStandByMode(bStandBy); + Util::SetStandByMode(standBy); - iResetCounter += iSleepInterval; - if (iResetCounter >= 1000) + resetCounter += sleepInterval; + if (resetCounter >= 1000) { // this code should not be called too often, once per second is OK g_pServerPool->CloseUnusedConnections(); ResetHangingDownloads(); - if (!bStandBy) + if (!standBy) { SavePartialState(); } - iResetCounter = 0; + resetCounter = 0; g_pStatMeter->IntervalCheck(); AdjustDownloadsLimit(); } @@ -295,7 +295,7 @@ void QueueCoordinator::Run() while (!completed) { DownloadQueue::Lock(); - completed = m_ActiveDownloads.size() == 0; + completed = m_activeDownloads.size() == 0; DownloadQueue::Unlock(); usleep(100 * 1000); ResetHangingDownloads(); @@ -312,120 +312,120 @@ void QueueCoordinator::Run() **/ void QueueCoordinator::AdjustDownloadsLimit() { - if (m_iServerConfigGeneration == g_pServerPool->GetGeneration()) + if (m_serverConfigGeneration == g_pServerPool->GetGeneration()) { return; } // two extra threads for completing files (when connections are not needed) - int iDownloadsLimit = 2; + int downloadsLimit = 2; // allow one thread per 0-level (main) and 1-level (backup) server connection for (Servers::iterator it = g_pServerPool->GetServers()->begin(); it != g_pServerPool->GetServers()->end(); it++) { - NewsServer* pNewsServer = *it; - if ((pNewsServer->GetNormLevel() == 0 || pNewsServer->GetNormLevel() == 1) && pNewsServer->GetActive()) + NewsServer* newsServer = *it; + if ((newsServer->GetNormLevel() == 0 || newsServer->GetNormLevel() == 1) && newsServer->GetActive()) { - iDownloadsLimit += pNewsServer->GetMaxConnections(); + downloadsLimit += newsServer->GetMaxConnections(); } } - m_iDownloadsLimit = iDownloadsLimit; + m_downloadsLimit = downloadsLimit; } -void QueueCoordinator::AddNZBFileToQueue(NZBFile* pNZBFile, NZBInfo* pUrlInfo, bool bAddFirst) +void QueueCoordinator::AddNZBFileToQueue(NZBFile* nzbFile, NZBInfo* urlInfo, bool addFirst) { debug("Adding NZBFile to queue"); - NZBInfo* pNZBInfo = pNZBFile->GetNZBInfo(); + NZBInfo* nzbInfo = nzbFile->GetNZBInfo(); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - DownloadQueue::Aspect foundAspect = { DownloadQueue::eaNzbFound, pDownloadQueue, pNZBInfo, NULL }; - pDownloadQueue->Notify(&foundAspect); + DownloadQueue::Aspect foundAspect = { DownloadQueue::eaNzbFound, downloadQueue, nzbInfo, NULL }; + downloadQueue->Notify(&foundAspect); - NZBInfo::EDeleteStatus eDeleteStatus = pNZBInfo->GetDeleteStatus(); + NZBInfo::EDeleteStatus deleteStatus = nzbInfo->GetDeleteStatus(); - if (eDeleteStatus != NZBInfo::dsNone) + if (deleteStatus != NZBInfo::dsNone) { - bool bAllPaused = !pNZBInfo->GetFileList()->empty(); - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + bool allPaused = !nzbInfo->GetFileList()->empty(); + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - bAllPaused &= pFileInfo->GetPaused(); + FileInfo* fileInfo = *it; + allPaused &= fileInfo->GetPaused(); if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) { - g_pDiskState->DiscardFile(pFileInfo, true, false, false); + g_pDiskState->DiscardFile(fileInfo, true, false, false); } } - pNZBInfo->SetDeletePaused(bAllPaused); + nzbInfo->SetDeletePaused(allPaused); } - if (eDeleteStatus != NZBInfo::dsManual) + if (deleteStatus != NZBInfo::dsManual) { // NZBInfo will be added either to queue or to history as duplicate // and therefore can be detached from NZBFile. - pNZBFile->DetachNZBInfo(); + nzbFile->DetachNZBInfo(); } - if (eDeleteStatus == NZBInfo::dsNone) + if (deleteStatus == NZBInfo::dsNone) { - if (g_pOptions->GetDupeCheck() && pNZBInfo->GetDupeMode() != dmForce) + if (g_pOptions->GetDupeCheck() && nzbInfo->GetDupeMode() != dmForce) { - CheckDupeFileInfos(pNZBInfo); + CheckDupeFileInfos(nzbInfo); } - if (pUrlInfo) + if (urlInfo) { // insert at the URL position - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pPosNzbInfo = *it; - if (pPosNzbInfo == pUrlInfo) + NZBInfo* posNzbInfo = *it; + if (posNzbInfo == urlInfo) { - pDownloadQueue->GetQueue()->insert(it, pNZBInfo); + downloadQueue->GetQueue()->insert(it, nzbInfo); break; } } } - else if (bAddFirst) + else if (addFirst) { - pDownloadQueue->GetQueue()->push_front(pNZBInfo); + downloadQueue->GetQueue()->push_front(nzbInfo); } else { - pDownloadQueue->GetQueue()->push_back(pNZBInfo); + downloadQueue->GetQueue()->push_back(nzbInfo); } } - if (pUrlInfo) + if (urlInfo) { - pNZBInfo->SetID(pUrlInfo->GetID()); - pDownloadQueue->GetQueue()->Remove(pUrlInfo); - delete pUrlInfo; + nzbInfo->SetID(urlInfo->GetID()); + downloadQueue->GetQueue()->Remove(urlInfo); + delete urlInfo; } - if (eDeleteStatus == NZBInfo::dsNone) + if (deleteStatus == NZBInfo::dsNone) { - pNZBInfo->PrintMessage(Message::mkInfo, "Collection %s added to queue", pNZBInfo->GetName()); + nzbInfo->PrintMessage(Message::mkInfo, "Collection %s added to queue", nzbInfo->GetName()); } - if (eDeleteStatus != NZBInfo::dsManual) + if (deleteStatus != NZBInfo::dsManual) { - DownloadQueue::Aspect addedAspect = { DownloadQueue::eaNzbAdded, pDownloadQueue, pNZBInfo, NULL }; - pDownloadQueue->Notify(&addedAspect); + DownloadQueue::Aspect addedAspect = { DownloadQueue::eaNzbAdded, downloadQueue, nzbInfo, NULL }; + downloadQueue->Notify(&addedAspect); } - pDownloadQueue->Save(); + downloadQueue->Save(); DownloadQueue::Unlock(); } -void QueueCoordinator::CheckDupeFileInfos(NZBInfo* pNZBInfo) +void QueueCoordinator::CheckDupeFileInfos(NZBInfo* nzbInfo) { debug("CheckDupeFileInfos"); - if (!g_pOptions->GetDupeCheck() || pNZBInfo->GetDupeMode() == dmForce) + if (!g_pOptions->GetDupeCheck() || nzbInfo->GetDupeMode() == dmForce) { return; } @@ -433,42 +433,42 @@ void QueueCoordinator::CheckDupeFileInfos(NZBInfo* pNZBInfo) FileList dupeList(true); int index1 = 0; - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { index1++; - FileInfo* pFileInfo = *it; + FileInfo* fileInfo = *it; bool dupe = false; int index2 = 0; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { index2++; - FileInfo* pFileInfo2 = *it2; - if (pFileInfo != pFileInfo2 && - !strcmp(pFileInfo->GetFilename(), pFileInfo2->GetFilename()) && - (pFileInfo->GetSize() < pFileInfo2->GetSize() || - (pFileInfo->GetSize() == pFileInfo2->GetSize() && index2 < index1))) + FileInfo* fileInfo2 = *it2; + if (fileInfo != fileInfo2 && + !strcmp(fileInfo->GetFilename(), fileInfo2->GetFilename()) && + (fileInfo->GetSize() < fileInfo2->GetSize() || + (fileInfo->GetSize() == fileInfo2->GetSize() && index2 < index1))) { - warn("File \"%s\" appears twice in collection, adding only the biggest file", pFileInfo->GetFilename()); + warn("File \"%s\" appears twice in collection, adding only the biggest file", fileInfo->GetFilename()); dupe = true; break; } } if (dupe) { - dupeList.push_back(pFileInfo); + dupeList.push_back(fileInfo); continue; } } for (FileList::iterator it = dupeList.begin(); it != dupeList.end(); it++) { - FileInfo* pFileInfo = *it; - StatFileInfo(pFileInfo, false); - pNZBInfo->GetFileList()->Remove(pFileInfo); + FileInfo* fileInfo = *it; + StatFileInfo(fileInfo, false); + nzbInfo->GetFileList()->Remove(fileInfo); if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) { - g_pDiskState->DiscardFile(pFileInfo, true, false, false); + g_pDiskState->DiscardFile(fileInfo, true, false, false); } } } @@ -479,7 +479,7 @@ void QueueCoordinator::Stop() debug("Stopping ArticleDownloads"); DownloadQueue::Lock(); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { (*it)->Stop(); } @@ -490,7 +490,7 @@ void QueueCoordinator::Stop() /* * Returns next article for download. */ -bool QueueCoordinator::GetNextArticle(DownloadQueue* pDownloadQueue, FileInfo* &pFileInfo, ArticleInfo* &pArticleInfo) +bool QueueCoordinator::GetNextArticle(DownloadQueue* downloadQueue, FileInfo* &fileInfo, ArticleInfo* &articleInfo) { // find an unpaused file with the highest priority, then take the next article from the file. // if the file doesn't have any articles left for download, we store that fact and search again, @@ -501,340 +501,340 @@ bool QueueCoordinator::GetNextArticle(DownloadQueue* pDownloadQueue, FileInfo* & //debug("QueueCoordinator::GetNextArticle()"); - bool bOK = false; + bool ok = false; // pCheckedFiles stores - bool* pCheckedFiles = NULL; - time_t tCurDate = time(NULL); + bool* checkedFiles = NULL; + time_t curDate = time(NULL); - while (!bOK) + while (!ok) { - pFileInfo = NULL; - int iNum = 0; - int iFileNum = 0; + fileInfo = NULL; + int num = 0; + int fileNum = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo1 = *it2; - if ((!pCheckedFiles || !pCheckedFiles[iNum]) && - !pFileInfo1->GetPaused() && !pFileInfo1->GetDeleted() && + FileInfo* fileInfo1 = *it2; + if ((!checkedFiles || !checkedFiles[num]) && + !fileInfo1->GetPaused() && !fileInfo1->GetDeleted() && (g_pOptions->GetPropagationDelay() == 0 || - (int)pFileInfo1->GetTime() < (int)tCurDate - g_pOptions->GetPropagationDelay()) && - (!g_pOptions->GetPauseDownload() || pNZBInfo->GetForcePriority()) && - (!pFileInfo || - (pFileInfo1->GetExtraPriority() == pFileInfo->GetExtraPriority() && - pFileInfo1->GetNZBInfo()->GetPriority() > pFileInfo->GetNZBInfo()->GetPriority()) || - (pFileInfo1->GetExtraPriority() > pFileInfo->GetExtraPriority()))) + (int)fileInfo1->GetTime() < (int)curDate - g_pOptions->GetPropagationDelay()) && + (!g_pOptions->GetPauseDownload() || nzbInfo->GetForcePriority()) && + (!fileInfo || + (fileInfo1->GetExtraPriority() == fileInfo->GetExtraPriority() && + fileInfo1->GetNZBInfo()->GetPriority() > fileInfo->GetNZBInfo()->GetPriority()) || + (fileInfo1->GetExtraPriority() > fileInfo->GetExtraPriority()))) { - pFileInfo = pFileInfo1; - iFileNum = iNum; + fileInfo = fileInfo1; + fileNum = num; } - iNum++; + num++; } } - if (!pFileInfo) + if (!fileInfo) { // there are no more files for download break; } - if (pFileInfo->GetArticles()->empty() && g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) + if (fileInfo->GetArticles()->empty() && g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode()) { - g_pDiskState->LoadArticles(pFileInfo); + g_pDiskState->LoadArticles(fileInfo); } // check if the file has any articles left for download - for (FileInfo::Articles::iterator at = pFileInfo->GetArticles()->begin(); at != pFileInfo->GetArticles()->end(); at++) + for (FileInfo::Articles::iterator at = fileInfo->GetArticles()->begin(); at != fileInfo->GetArticles()->end(); at++) { - pArticleInfo = *at; - if (pArticleInfo->GetStatus() == ArticleInfo::aiUndefined) + articleInfo = *at; + if (articleInfo->GetStatus() == ArticleInfo::aiUndefined) { - bOK = true; + ok = true; break; } } - if (!bOK) + if (!ok) { // the file doesn't have any articles left for download, we mark the file as such - if (!pCheckedFiles) + if (!checkedFiles) { - int iTotalFileCount = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + int totalFileCount = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - iTotalFileCount += pNZBInfo->GetFileList()->size(); + NZBInfo* nzbInfo = *it; + totalFileCount += nzbInfo->GetFileList()->size(); } - if (iTotalFileCount > 0) + if (totalFileCount > 0) { - int iArrSize = sizeof(bool) * iTotalFileCount; - pCheckedFiles = (bool*)malloc(iArrSize); - memset(pCheckedFiles, false, iArrSize); + int arrSize = sizeof(bool) * totalFileCount; + checkedFiles = (bool*)malloc(arrSize); + memset(checkedFiles, false, arrSize); } } - if (pCheckedFiles) + if (checkedFiles) { - pCheckedFiles[iFileNum] = true; + checkedFiles[fileNum] = true; } } } - free(pCheckedFiles); + free(checkedFiles); - return bOK; + return ok; } -void QueueCoordinator::StartArticleDownload(FileInfo* pFileInfo, ArticleInfo* pArticleInfo, NNTPConnection* pConnection) +void QueueCoordinator::StartArticleDownload(FileInfo* fileInfo, ArticleInfo* articleInfo, NNTPConnection* connection) { debug("Starting new ArticleDownloader"); - ArticleDownloader* pArticleDownloader = new ArticleDownloader(); - pArticleDownloader->SetAutoDestroy(true); - pArticleDownloader->Attach(this); - pArticleDownloader->SetFileInfo(pFileInfo); - pArticleDownloader->SetArticleInfo(pArticleInfo); - pArticleDownloader->SetConnection(pConnection); + ArticleDownloader* articleDownloader = new ArticleDownloader(); + articleDownloader->SetAutoDestroy(true); + articleDownloader->Attach(this); + articleDownloader->SetFileInfo(fileInfo); + articleDownloader->SetArticleInfo(articleInfo); + articleDownloader->SetConnection(connection); - char szInfoName[1024]; - snprintf(szInfoName, 1024, "%s%c%s [%i/%i]", pFileInfo->GetNZBInfo()->GetName(), (int)PATH_SEPARATOR, pFileInfo->GetFilename(), pArticleInfo->GetPartNumber(), (int)pFileInfo->GetArticles()->size()); - szInfoName[1024-1] = '\0'; - pArticleDownloader->SetInfoName(szInfoName); + char infoName[1024]; + snprintf(infoName, 1024, "%s%c%s [%i/%i]", fileInfo->GetNZBInfo()->GetName(), (int)PATH_SEPARATOR, fileInfo->GetFilename(), articleInfo->GetPartNumber(), (int)fileInfo->GetArticles()->size()); + infoName[1024-1] = '\0'; + articleDownloader->SetInfoName(infoName); - pArticleInfo->SetStatus(ArticleInfo::aiRunning); - pFileInfo->SetActiveDownloads(pFileInfo->GetActiveDownloads() + 1); - pFileInfo->GetNZBInfo()->SetActiveDownloads(pFileInfo->GetNZBInfo()->GetActiveDownloads() + 1); + articleInfo->SetStatus(ArticleInfo::aiRunning); + fileInfo->SetActiveDownloads(fileInfo->GetActiveDownloads() + 1); + fileInfo->GetNZBInfo()->SetActiveDownloads(fileInfo->GetNZBInfo()->GetActiveDownloads() + 1); - m_ActiveDownloads.push_back(pArticleDownloader); - pArticleDownloader->Start(); + m_activeDownloads.push_back(articleDownloader); + articleDownloader->Start(); } void QueueCoordinator::Update(Subject* Caller, void* Aspect) { debug("Notification from ArticleDownloader received"); - ArticleDownloader* pArticleDownloader = (ArticleDownloader*)Caller; - if ((pArticleDownloader->GetStatus() == ArticleDownloader::adFinished) || - (pArticleDownloader->GetStatus() == ArticleDownloader::adFailed) || - (pArticleDownloader->GetStatus() == ArticleDownloader::adRetry)) + ArticleDownloader* articleDownloader = (ArticleDownloader*)Caller; + if ((articleDownloader->GetStatus() == ArticleDownloader::adFinished) || + (articleDownloader->GetStatus() == ArticleDownloader::adFailed) || + (articleDownloader->GetStatus() == ArticleDownloader::adRetry)) { - ArticleCompleted(pArticleDownloader); + ArticleCompleted(articleDownloader); } } -void QueueCoordinator::ArticleCompleted(ArticleDownloader* pArticleDownloader) +void QueueCoordinator::ArticleCompleted(ArticleDownloader* articleDownloader) { debug("Article downloaded"); - FileInfo* pFileInfo = pArticleDownloader->GetFileInfo(); - NZBInfo* pNZBInfo = pFileInfo->GetNZBInfo(); - ArticleInfo* pArticleInfo = pArticleDownloader->GetArticleInfo(); - bool bRetry = false; + FileInfo* fileInfo = articleDownloader->GetFileInfo(); + NZBInfo* nzbInfo = fileInfo->GetNZBInfo(); + ArticleInfo* articleInfo = articleDownloader->GetArticleInfo(); + bool retry = false; bool fileCompleted = false; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - if (pArticleDownloader->GetStatus() == ArticleDownloader::adFinished) + if (articleDownloader->GetStatus() == ArticleDownloader::adFinished) { - pArticleInfo->SetStatus(ArticleInfo::aiFinished); - pFileInfo->SetSuccessSize(pFileInfo->GetSuccessSize() + pArticleInfo->GetSize()); - pNZBInfo->SetCurrentSuccessSize(pNZBInfo->GetCurrentSuccessSize() + pArticleInfo->GetSize()); - pNZBInfo->SetParCurrentSuccessSize(pNZBInfo->GetParCurrentSuccessSize() + (pFileInfo->GetParFile() ? pArticleInfo->GetSize() : 0)); - pFileInfo->SetSuccessArticles(pFileInfo->GetSuccessArticles() + 1); - pNZBInfo->SetCurrentSuccessArticles(pNZBInfo->GetCurrentSuccessArticles() + 1); + articleInfo->SetStatus(ArticleInfo::aiFinished); + fileInfo->SetSuccessSize(fileInfo->GetSuccessSize() + articleInfo->GetSize()); + nzbInfo->SetCurrentSuccessSize(nzbInfo->GetCurrentSuccessSize() + articleInfo->GetSize()); + nzbInfo->SetParCurrentSuccessSize(nzbInfo->GetParCurrentSuccessSize() + (fileInfo->GetParFile() ? articleInfo->GetSize() : 0)); + fileInfo->SetSuccessArticles(fileInfo->GetSuccessArticles() + 1); + nzbInfo->SetCurrentSuccessArticles(nzbInfo->GetCurrentSuccessArticles() + 1); } - else if (pArticleDownloader->GetStatus() == ArticleDownloader::adFailed) + else if (articleDownloader->GetStatus() == ArticleDownloader::adFailed) { - pArticleInfo->SetStatus(ArticleInfo::aiFailed); - pFileInfo->SetFailedSize(pFileInfo->GetFailedSize() + pArticleInfo->GetSize()); - pNZBInfo->SetCurrentFailedSize(pNZBInfo->GetCurrentFailedSize() + pArticleInfo->GetSize()); - pNZBInfo->SetParCurrentFailedSize(pNZBInfo->GetParCurrentFailedSize() + (pFileInfo->GetParFile() ? pArticleInfo->GetSize() : 0)); - pFileInfo->SetFailedArticles(pFileInfo->GetFailedArticles() + 1); - pNZBInfo->SetCurrentFailedArticles(pNZBInfo->GetCurrentFailedArticles() + 1); + articleInfo->SetStatus(ArticleInfo::aiFailed); + fileInfo->SetFailedSize(fileInfo->GetFailedSize() + articleInfo->GetSize()); + nzbInfo->SetCurrentFailedSize(nzbInfo->GetCurrentFailedSize() + articleInfo->GetSize()); + nzbInfo->SetParCurrentFailedSize(nzbInfo->GetParCurrentFailedSize() + (fileInfo->GetParFile() ? articleInfo->GetSize() : 0)); + fileInfo->SetFailedArticles(fileInfo->GetFailedArticles() + 1); + nzbInfo->SetCurrentFailedArticles(nzbInfo->GetCurrentFailedArticles() + 1); } - else if (pArticleDownloader->GetStatus() == ArticleDownloader::adRetry) + else if (articleDownloader->GetStatus() == ArticleDownloader::adRetry) { - pArticleInfo->SetStatus(ArticleInfo::aiUndefined); - bRetry = true; + articleInfo->SetStatus(ArticleInfo::aiUndefined); + retry = true; } - if (!bRetry) + if (!retry) { - pFileInfo->SetRemainingSize(pFileInfo->GetRemainingSize() - pArticleInfo->GetSize()); - pNZBInfo->SetRemainingSize(pNZBInfo->GetRemainingSize() - pArticleInfo->GetSize()); - if (pFileInfo->GetPaused()) + fileInfo->SetRemainingSize(fileInfo->GetRemainingSize() - articleInfo->GetSize()); + nzbInfo->SetRemainingSize(nzbInfo->GetRemainingSize() - articleInfo->GetSize()); + if (fileInfo->GetPaused()) { - pNZBInfo->SetPausedSize(pNZBInfo->GetPausedSize() - pArticleInfo->GetSize()); + nzbInfo->SetPausedSize(nzbInfo->GetPausedSize() - articleInfo->GetSize()); } - pFileInfo->SetCompletedArticles(pFileInfo->GetCompletedArticles() + 1); - fileCompleted = (int)pFileInfo->GetArticles()->size() == pFileInfo->GetCompletedArticles(); - pFileInfo->GetServerStats()->ListOp(pArticleDownloader->GetServerStats(), ServerStatList::soAdd); - pNZBInfo->GetCurrentServerStats()->ListOp(pArticleDownloader->GetServerStats(), ServerStatList::soAdd); - pFileInfo->SetPartialChanged(true); + fileInfo->SetCompletedArticles(fileInfo->GetCompletedArticles() + 1); + fileCompleted = (int)fileInfo->GetArticles()->size() == fileInfo->GetCompletedArticles(); + fileInfo->GetServerStats()->ListOp(articleDownloader->GetServerStats(), ServerStatList::soAdd); + nzbInfo->GetCurrentServerStats()->ListOp(articleDownloader->GetServerStats(), ServerStatList::soAdd); + fileInfo->SetPartialChanged(true); } - if (!pFileInfo->GetFilenameConfirmed() && - pArticleDownloader->GetStatus() == ArticleDownloader::adFinished && - pArticleDownloader->GetArticleFilename()) + if (!fileInfo->GetFilenameConfirmed() && + articleDownloader->GetStatus() == ArticleDownloader::adFinished && + articleDownloader->GetArticleFilename()) { - pFileInfo->SetFilename(pArticleDownloader->GetArticleFilename()); - pFileInfo->SetFilenameConfirmed(true); + fileInfo->SetFilename(articleDownloader->GetArticleFilename()); + fileInfo->SetFilenameConfirmed(true); if (g_pOptions->GetDupeCheck() && - pNZBInfo->GetDupeMode() != dmForce && - !pNZBInfo->GetManyDupeFiles() && - Util::FileExists(pNZBInfo->GetDestDir(), pFileInfo->GetFilename())) + nzbInfo->GetDupeMode() != dmForce && + !nzbInfo->GetManyDupeFiles() && + Util::FileExists(nzbInfo->GetDestDir(), fileInfo->GetFilename())) { - warn("File \"%s\" seems to be duplicate, cancelling download and deleting file from queue", pFileInfo->GetFilename()); + warn("File \"%s\" seems to be duplicate, cancelling download and deleting file from queue", fileInfo->GetFilename()); fileCompleted = false; - pFileInfo->SetAutoDeleted(true); - DeleteQueueEntry(pDownloadQueue, pFileInfo); + fileInfo->SetAutoDeleted(true); + DeleteQueueEntry(downloadQueue, fileInfo); } } - pNZBInfo->SetDownloadedSize(pNZBInfo->GetDownloadedSize() + pArticleDownloader->GetDownloadedSize()); + nzbInfo->SetDownloadedSize(nzbInfo->GetDownloadedSize() + articleDownloader->GetDownloadedSize()); bool deleteFileObj = false; - if (fileCompleted && !pFileInfo->GetDeleted()) + if (fileCompleted && !fileInfo->GetDeleted()) { // all jobs done DownloadQueue::Unlock(); - pArticleDownloader->CompleteFileParts(); - pDownloadQueue = DownloadQueue::Lock(); + articleDownloader->CompleteFileParts(); + downloadQueue = DownloadQueue::Lock(); deleteFileObj = true; } - CheckHealth(pDownloadQueue, pFileInfo); + CheckHealth(downloadQueue, fileInfo); bool hasOtherDownloaders = false; - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { - ArticleDownloader* pDownloader = *it; - if (pDownloader != pArticleDownloader && pDownloader->GetFileInfo() == pFileInfo) + ArticleDownloader* downloader = *it; + if (downloader != articleDownloader && downloader->GetFileInfo() == fileInfo) { hasOtherDownloaders = true; break; } } - deleteFileObj |= pFileInfo->GetDeleted() && !hasOtherDownloaders; + deleteFileObj |= fileInfo->GetDeleted() && !hasOtherDownloaders; // remove downloader from downloader list - m_ActiveDownloads.erase(std::find(m_ActiveDownloads.begin(), m_ActiveDownloads.end(), pArticleDownloader)); + m_activeDownloads.erase(std::find(m_activeDownloads.begin(), m_activeDownloads.end(), articleDownloader)); - pFileInfo->SetActiveDownloads(pFileInfo->GetActiveDownloads() - 1); - pNZBInfo->SetActiveDownloads(pNZBInfo->GetActiveDownloads() - 1); + fileInfo->SetActiveDownloads(fileInfo->GetActiveDownloads() - 1); + nzbInfo->SetActiveDownloads(nzbInfo->GetActiveDownloads() - 1); if (deleteFileObj) { - DeleteFileInfo(pDownloadQueue, pFileInfo, fileCompleted); - pDownloadQueue->Save(); + DeleteFileInfo(downloadQueue, fileInfo, fileCompleted); + downloadQueue->Save(); } DownloadQueue::Unlock(); } -void QueueCoordinator::StatFileInfo(FileInfo* pFileInfo, bool bCompleted) +void QueueCoordinator::StatFileInfo(FileInfo* fileInfo, bool completed) { - NZBInfo* pNZBInfo = pFileInfo->GetNZBInfo(); - if (bCompleted || pNZBInfo->GetDeleting()) + NZBInfo* nzbInfo = fileInfo->GetNZBInfo(); + if (completed || nzbInfo->GetDeleting()) { - pNZBInfo->SetSuccessSize(pNZBInfo->GetSuccessSize() + pFileInfo->GetSuccessSize()); - pNZBInfo->SetFailedSize(pNZBInfo->GetFailedSize() + pFileInfo->GetFailedSize()); - pNZBInfo->SetFailedArticles(pNZBInfo->GetFailedArticles() + pFileInfo->GetFailedArticles() + pFileInfo->GetMissedArticles()); - pNZBInfo->SetSuccessArticles(pNZBInfo->GetSuccessArticles() + pFileInfo->GetSuccessArticles()); - if (pFileInfo->GetParFile()) + nzbInfo->SetSuccessSize(nzbInfo->GetSuccessSize() + fileInfo->GetSuccessSize()); + nzbInfo->SetFailedSize(nzbInfo->GetFailedSize() + fileInfo->GetFailedSize()); + nzbInfo->SetFailedArticles(nzbInfo->GetFailedArticles() + fileInfo->GetFailedArticles() + fileInfo->GetMissedArticles()); + nzbInfo->SetSuccessArticles(nzbInfo->GetSuccessArticles() + fileInfo->GetSuccessArticles()); + if (fileInfo->GetParFile()) { - pNZBInfo->SetParSuccessSize(pNZBInfo->GetParSuccessSize() + pFileInfo->GetSuccessSize()); - pNZBInfo->SetParFailedSize(pNZBInfo->GetParFailedSize() + pFileInfo->GetFailedSize()); + nzbInfo->SetParSuccessSize(nzbInfo->GetParSuccessSize() + fileInfo->GetSuccessSize()); + nzbInfo->SetParFailedSize(nzbInfo->GetParFailedSize() + fileInfo->GetFailedSize()); } - pNZBInfo->GetServerStats()->ListOp(pFileInfo->GetServerStats(), ServerStatList::soAdd); + nzbInfo->GetServerStats()->ListOp(fileInfo->GetServerStats(), ServerStatList::soAdd); } - else if (!pNZBInfo->GetDeleting() && !pNZBInfo->GetParCleanup()) + else if (!nzbInfo->GetDeleting() && !nzbInfo->GetParCleanup()) { // file deleted but not the whole nzb and not par-cleanup - pNZBInfo->SetFileCount(pNZBInfo->GetFileCount() - 1); - pNZBInfo->SetSize(pNZBInfo->GetSize() - pFileInfo->GetSize()); - pNZBInfo->SetCurrentSuccessSize(pNZBInfo->GetCurrentSuccessSize() - pFileInfo->GetSuccessSize()); - pNZBInfo->SetFailedSize(pNZBInfo->GetFailedSize() - pFileInfo->GetMissedSize()); - pNZBInfo->SetCurrentFailedSize(pNZBInfo->GetCurrentFailedSize() - pFileInfo->GetFailedSize() - pFileInfo->GetMissedSize()); - pNZBInfo->SetTotalArticles(pNZBInfo->GetTotalArticles() - pFileInfo->GetTotalArticles()); - pNZBInfo->SetCurrentSuccessArticles(pNZBInfo->GetCurrentSuccessArticles() - pFileInfo->GetSuccessArticles()); - pNZBInfo->SetCurrentFailedArticles(pNZBInfo->GetCurrentFailedArticles() - pFileInfo->GetFailedArticles()); - pNZBInfo->GetCurrentServerStats()->ListOp(pFileInfo->GetServerStats(), ServerStatList::soSubtract); - if (pFileInfo->GetParFile()) + nzbInfo->SetFileCount(nzbInfo->GetFileCount() - 1); + nzbInfo->SetSize(nzbInfo->GetSize() - fileInfo->GetSize()); + nzbInfo->SetCurrentSuccessSize(nzbInfo->GetCurrentSuccessSize() - fileInfo->GetSuccessSize()); + nzbInfo->SetFailedSize(nzbInfo->GetFailedSize() - fileInfo->GetMissedSize()); + nzbInfo->SetCurrentFailedSize(nzbInfo->GetCurrentFailedSize() - fileInfo->GetFailedSize() - fileInfo->GetMissedSize()); + nzbInfo->SetTotalArticles(nzbInfo->GetTotalArticles() - fileInfo->GetTotalArticles()); + nzbInfo->SetCurrentSuccessArticles(nzbInfo->GetCurrentSuccessArticles() - fileInfo->GetSuccessArticles()); + nzbInfo->SetCurrentFailedArticles(nzbInfo->GetCurrentFailedArticles() - fileInfo->GetFailedArticles()); + nzbInfo->GetCurrentServerStats()->ListOp(fileInfo->GetServerStats(), ServerStatList::soSubtract); + if (fileInfo->GetParFile()) { - pNZBInfo->SetParSize(pNZBInfo->GetParSize() - pFileInfo->GetSize()); - pNZBInfo->SetParCurrentSuccessSize(pNZBInfo->GetParCurrentSuccessSize() - pFileInfo->GetSuccessSize()); - pNZBInfo->SetParFailedSize(pNZBInfo->GetParFailedSize() - pFileInfo->GetMissedSize()); - pNZBInfo->SetParCurrentFailedSize(pNZBInfo->GetParCurrentFailedSize() - pFileInfo->GetFailedSize() - pFileInfo->GetMissedSize()); + nzbInfo->SetParSize(nzbInfo->GetParSize() - fileInfo->GetSize()); + nzbInfo->SetParCurrentSuccessSize(nzbInfo->GetParCurrentSuccessSize() - fileInfo->GetSuccessSize()); + nzbInfo->SetParFailedSize(nzbInfo->GetParFailedSize() - fileInfo->GetMissedSize()); + nzbInfo->SetParCurrentFailedSize(nzbInfo->GetParCurrentFailedSize() - fileInfo->GetFailedSize() - fileInfo->GetMissedSize()); } - pNZBInfo->SetRemainingSize(pNZBInfo->GetRemainingSize() - pFileInfo->GetRemainingSize()); - if (pFileInfo->GetPaused()) + nzbInfo->SetRemainingSize(nzbInfo->GetRemainingSize() - fileInfo->GetRemainingSize()); + if (fileInfo->GetPaused()) { - pNZBInfo->SetPausedSize(pNZBInfo->GetPausedSize() - pFileInfo->GetRemainingSize()); + nzbInfo->SetPausedSize(nzbInfo->GetPausedSize() - fileInfo->GetRemainingSize()); } } - if (pFileInfo->GetParFile()) + if (fileInfo->GetParFile()) { - pNZBInfo->SetRemainingParCount(pNZBInfo->GetRemainingParCount() - 1); + nzbInfo->SetRemainingParCount(nzbInfo->GetRemainingParCount() - 1); } - if (pFileInfo->GetPaused()) + if (fileInfo->GetPaused()) { - pNZBInfo->SetPausedFileCount(pNZBInfo->GetPausedFileCount() - 1); + nzbInfo->SetPausedFileCount(nzbInfo->GetPausedFileCount() - 1); } } -void QueueCoordinator::DeleteFileInfo(DownloadQueue* pDownloadQueue, FileInfo* pFileInfo, bool bCompleted) +void QueueCoordinator::DeleteFileInfo(DownloadQueue* downloadQueue, FileInfo* fileInfo, bool completed) { - while (g_pArticleCache->FileBusy(pFileInfo)) + while (g_pArticleCache->FileBusy(fileInfo)) { usleep(5*1000); } - bool fileDeleted = pFileInfo->GetDeleted(); - pFileInfo->SetDeleted(true); + bool fileDeleted = fileInfo->GetDeleted(); + fileInfo->SetDeleted(true); - StatFileInfo(pFileInfo, bCompleted); + StatFileInfo(fileInfo, completed); if (g_pOptions->GetSaveQueue() && g_pOptions->GetServerMode() && - (!bCompleted || (pFileInfo->GetMissedArticles() == 0 && pFileInfo->GetFailedArticles() == 0))) + (!completed || (fileInfo->GetMissedArticles() == 0 && fileInfo->GetFailedArticles() == 0))) { - g_pDiskState->DiscardFile(pFileInfo, true, true, false); + g_pDiskState->DiscardFile(fileInfo, true, true, false); } - if (!bCompleted) + if (!completed) { - DiscardDiskFile(pFileInfo); + DiscardDiskFile(fileInfo); } - NZBInfo* pNZBInfo = pFileInfo->GetNZBInfo(); + NZBInfo* nzbInfo = fileInfo->GetNZBInfo(); - DownloadQueue::Aspect aspect = { bCompleted && !fileDeleted ? + DownloadQueue::Aspect aspect = { completed && !fileDeleted ? DownloadQueue::eaFileCompleted : DownloadQueue::eaFileDeleted, - pDownloadQueue, pNZBInfo, pFileInfo }; - pDownloadQueue->Notify(&aspect); + downloadQueue, nzbInfo, fileInfo }; + downloadQueue->Notify(&aspect); // nzb-file could be deleted from queue in "Notify", check if it is still in queue. - if (std::find(pDownloadQueue->GetQueue()->begin(), pDownloadQueue->GetQueue()->end(), pNZBInfo) != - pDownloadQueue->GetQueue()->end()) + if (std::find(downloadQueue->GetQueue()->begin(), downloadQueue->GetQueue()->end(), nzbInfo) != + downloadQueue->GetQueue()->end()) { - pNZBInfo->GetFileList()->Remove(pFileInfo); - delete pFileInfo; + nzbInfo->GetFileList()->Remove(fileInfo); + delete fileInfo; } } -void QueueCoordinator::DiscardDiskFile(FileInfo* pFileInfo) +void QueueCoordinator::DiscardDiskFile(FileInfo* fileInfo) { // deleting temporary files if (!g_pOptions->GetDirectWrite()) { - for (FileInfo::Articles::iterator it = pFileInfo->GetArticles()->begin(); it != pFileInfo->GetArticles()->end(); it++) + for (FileInfo::Articles::iterator it = fileInfo->GetArticles()->begin(); it != fileInfo->GetArticles()->end(); it++) { ArticleInfo* pa = *it; if (pa->GetResultFilename()) @@ -844,9 +844,9 @@ void QueueCoordinator::DiscardDiskFile(FileInfo* pFileInfo) } } - if (g_pOptions->GetDirectWrite() && pFileInfo->GetOutputFilename()) + if (g_pOptions->GetDirectWrite() && fileInfo->GetOutputFilename()) { - remove(pFileInfo->GetOutputFilename()); + remove(fileInfo->GetOutputFilename()); } } @@ -857,19 +857,19 @@ void QueueCoordinator::SavePartialState() return; } - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - if (pFileInfo->GetPartialChanged()) + FileInfo* fileInfo = *it2; + if (fileInfo->GetPartialChanged()) { - debug("Saving partial state for %s", pFileInfo->GetFilename()); - g_pDiskState->SaveFileState(pFileInfo, false); - pFileInfo->SetPartialChanged(false); + debug("Saving partial state for %s", fileInfo->GetFilename()); + g_pDiskState->SaveFileState(fileInfo, false); + fileInfo->SetPartialChanged(false); } } } @@ -877,55 +877,55 @@ void QueueCoordinator::SavePartialState() DownloadQueue::Unlock(); } -void QueueCoordinator::CheckHealth(DownloadQueue* pDownloadQueue, FileInfo* pFileInfo) +void QueueCoordinator::CheckHealth(DownloadQueue* downloadQueue, FileInfo* fileInfo) { if (g_pOptions->GetHealthCheck() == Options::hcNone || - pFileInfo->GetNZBInfo()->GetHealthPaused() || - pFileInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsHealth || - pFileInfo->GetNZBInfo()->CalcHealth() >= pFileInfo->GetNZBInfo()->CalcCriticalHealth(true) || + fileInfo->GetNZBInfo()->GetHealthPaused() || + fileInfo->GetNZBInfo()->GetDeleteStatus() == NZBInfo::dsHealth || + fileInfo->GetNZBInfo()->CalcHealth() >= fileInfo->GetNZBInfo()->CalcCriticalHealth(true) || (g_pOptions->GetParScan() == Options::psDupe && g_pOptions->GetHealthCheck() == Options::hcDelete && - pFileInfo->GetNZBInfo()->GetSuccessArticles() * 100 / pFileInfo->GetNZBInfo()->GetTotalArticles() > 10)) + fileInfo->GetNZBInfo()->GetSuccessArticles() * 100 / fileInfo->GetNZBInfo()->GetTotalArticles() > 10)) { return; } if (g_pOptions->GetHealthCheck() == Options::hcPause) { - warn("Pausing %s due to health %.1f%% below critical %.1f%%", pFileInfo->GetNZBInfo()->GetName(), - pFileInfo->GetNZBInfo()->CalcHealth() / 10.0, pFileInfo->GetNZBInfo()->CalcCriticalHealth(true) / 10.0); - pFileInfo->GetNZBInfo()->SetHealthPaused(true); - pDownloadQueue->EditEntry(pFileInfo->GetNZBInfo()->GetID(), DownloadQueue::eaGroupPause, 0, NULL); + warn("Pausing %s due to health %.1f%% below critical %.1f%%", fileInfo->GetNZBInfo()->GetName(), + fileInfo->GetNZBInfo()->CalcHealth() / 10.0, fileInfo->GetNZBInfo()->CalcCriticalHealth(true) / 10.0); + fileInfo->GetNZBInfo()->SetHealthPaused(true); + downloadQueue->EditEntry(fileInfo->GetNZBInfo()->GetID(), DownloadQueue::eaGroupPause, 0, NULL); } else if (g_pOptions->GetHealthCheck() == Options::hcDelete) { - pFileInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, + fileInfo->GetNZBInfo()->PrintMessage(Message::mkWarning, "Cancelling download and deleting %s due to health %.1f%% below critical %.1f%%", - pFileInfo->GetNZBInfo()->GetName(), pFileInfo->GetNZBInfo()->CalcHealth() / 10.0, - pFileInfo->GetNZBInfo()->CalcCriticalHealth(true) / 10.0); - pFileInfo->GetNZBInfo()->SetDeleteStatus(NZBInfo::dsHealth); - pDownloadQueue->EditEntry(pFileInfo->GetNZBInfo()->GetID(), DownloadQueue::eaGroupDelete, 0, NULL); + fileInfo->GetNZBInfo()->GetName(), fileInfo->GetNZBInfo()->CalcHealth() / 10.0, + fileInfo->GetNZBInfo()->CalcCriticalHealth(true) / 10.0); + fileInfo->GetNZBInfo()->SetDeleteStatus(NZBInfo::dsHealth); + downloadQueue->EditEntry(fileInfo->GetNZBInfo()->GetID(), DownloadQueue::eaGroupDelete, 0, NULL); } } void QueueCoordinator::LogDebugInfo() { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); info(" ---------- Queue"); - long long lRemaining, lRemainingForced; - pDownloadQueue->CalcRemainingSize(&lRemaining, &lRemainingForced); - info(" Remaining: %.1f MB, Forced: %.1f MB", lRemaining / 1024.0 / 1024.0, lRemainingForced / 1024.0 / 1024.0); + long long remaining, remainingForced; + downloadQueue->CalcRemainingSize(&remaining, &remainingForced); + info(" Remaining: %.1f MB, Forced: %.1f MB", remaining / 1024.0 / 1024.0, remainingForced / 1024.0 / 1024.0); info(" Download: %s, Post-process: %s, Scan: %s", (g_pOptions->GetPauseDownload() ? "paused" : g_pOptions->GetTempPauseDownload() ? "temp-paused" : "active"), (g_pOptions->GetPausePostProcess() ? "paused" : "active"), (g_pOptions->GetPauseScan() ? "paused" : "active")); info(" ---------- QueueCoordinator"); - info(" Active Downloads: %i, Limit: %i", m_ActiveDownloads.size(), m_iDownloadsLimit); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + info(" Active Downloads: %i, Limit: %i", m_activeDownloads.size(), m_downloadsLimit); + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { - ArticleDownloader* pArticleDownloader = *it; - pArticleDownloader->LogDebugInfo(); + ArticleDownloader* articleDownloader = *it; + articleDownloader->LogDebugInfo(); } DownloadQueue::Unlock(); } @@ -940,43 +940,43 @@ void QueueCoordinator::ResetHangingDownloads() DownloadQueue::Lock(); time_t tm = ::time(NULL); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end();) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end();) { - ArticleDownloader* pArticleDownloader = *it; + ArticleDownloader* articleDownloader = *it; - if (tm - pArticleDownloader->GetLastUpdateTime() > g_pOptions->GetArticleTimeout() + 1 && - pArticleDownloader->GetStatus() == ArticleDownloader::adRunning) + if (tm - articleDownloader->GetLastUpdateTime() > g_pOptions->GetArticleTimeout() + 1 && + articleDownloader->GetStatus() == ArticleDownloader::adRunning) { - error("Cancelling hanging download %s @ %s", pArticleDownloader->GetInfoName(), - pArticleDownloader->GetConnectionName()); - pArticleDownloader->Stop(); + error("Cancelling hanging download %s @ %s", articleDownloader->GetInfoName(), + articleDownloader->GetConnectionName()); + articleDownloader->Stop(); } - if (tm - pArticleDownloader->GetLastUpdateTime() > g_pOptions->GetTerminateTimeout() && - pArticleDownloader->GetStatus() == ArticleDownloader::adRunning) + if (tm - articleDownloader->GetLastUpdateTime() > g_pOptions->GetTerminateTimeout() && + articleDownloader->GetStatus() == ArticleDownloader::adRunning) { - ArticleInfo* pArticleInfo = pArticleDownloader->GetArticleInfo(); - debug("Terminating hanging download %s", pArticleDownloader->GetInfoName()); - if (pArticleDownloader->Terminate()) + ArticleInfo* articleInfo = articleDownloader->GetArticleInfo(); + debug("Terminating hanging download %s", articleDownloader->GetInfoName()); + if (articleDownloader->Terminate()) { - error("Terminated hanging download %s @ %s", pArticleDownloader->GetInfoName(), - pArticleDownloader->GetConnectionName()); - pArticleInfo->SetStatus(ArticleInfo::aiUndefined); + error("Terminated hanging download %s @ %s", articleDownloader->GetInfoName(), + articleDownloader->GetConnectionName()); + articleInfo->SetStatus(ArticleInfo::aiUndefined); } else { - error("Could not terminate hanging download %s @ %s", pArticleDownloader->GetInfoName(), - pArticleDownloader->GetConnectionName()); + error("Could not terminate hanging download %s @ %s", articleDownloader->GetInfoName(), + articleDownloader->GetConnectionName()); } - m_ActiveDownloads.erase(it); + m_activeDownloads.erase(it); - pArticleDownloader->GetFileInfo()->SetActiveDownloads(pArticleDownloader->GetFileInfo()->GetActiveDownloads() - 1); - pArticleDownloader->GetFileInfo()->GetNZBInfo()->SetActiveDownloads(pArticleDownloader->GetFileInfo()->GetNZBInfo()->GetActiveDownloads() - 1); - pArticleDownloader->GetFileInfo()->GetNZBInfo()->SetDownloadedSize(pArticleDownloader->GetFileInfo()->GetNZBInfo()->GetDownloadedSize() + pArticleDownloader->GetDownloadedSize()); + articleDownloader->GetFileInfo()->SetActiveDownloads(articleDownloader->GetFileInfo()->GetActiveDownloads() - 1); + articleDownloader->GetFileInfo()->GetNZBInfo()->SetActiveDownloads(articleDownloader->GetFileInfo()->GetNZBInfo()->GetActiveDownloads() - 1); + articleDownloader->GetFileInfo()->GetNZBInfo()->SetDownloadedSize(articleDownloader->GetFileInfo()->GetNZBInfo()->GetDownloadedSize() + articleDownloader->GetDownloadedSize()); // it's not safe to destroy pArticleDownloader, because the state of object is unknown - delete pArticleDownloader; - it = m_ActiveDownloads.begin(); + delete articleDownloader; + it = m_activeDownloads.begin(); continue; } it++; @@ -989,173 +989,173 @@ void QueueCoordinator::ResetHangingDownloads() * Returns True if Entry was deleted from Queue or False if it was scheduled for Deletion. * NOTE: "False" does not mean unsuccess; the entry is (or will be) deleted in any case. */ -bool QueueCoordinator::DeleteQueueEntry(DownloadQueue* pDownloadQueue, FileInfo* pFileInfo) +bool QueueCoordinator::DeleteQueueEntry(DownloadQueue* downloadQueue, FileInfo* fileInfo) { - pFileInfo->SetDeleted(true); - bool bDownloading = false; - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + fileInfo->SetDeleted(true); + bool downloading = false; + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { - ArticleDownloader* pArticleDownloader = *it; - if (pArticleDownloader->GetFileInfo() == pFileInfo) + ArticleDownloader* articleDownloader = *it; + if (articleDownloader->GetFileInfo() == fileInfo) { - bDownloading = true; - pArticleDownloader->Stop(); + downloading = true; + articleDownloader->Stop(); } } - if (!bDownloading) + if (!downloading) { - DeleteFileInfo(pDownloadQueue, pFileInfo, false); + DeleteFileInfo(downloadQueue, fileInfo, false); } - return bDownloading; + return downloading; } -bool QueueCoordinator::SetQueueEntryCategory(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szCategory) +bool QueueCoordinator::SetQueueEntryCategory(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* category) { - if (pNZBInfo->GetPostInfo()) + if (nzbInfo->GetPostInfo()) { - error("Could not change category for %s. File in post-process-stage", pNZBInfo->GetName()); + error("Could not change category for %s. File in post-process-stage", nzbInfo->GetName()); return false; } - char szOldDestDir[1024]; - strncpy(szOldDestDir, pNZBInfo->GetDestDir(), 1024); - szOldDestDir[1024-1] = '\0'; + char oldDestDir[1024]; + strncpy(oldDestDir, nzbInfo->GetDestDir(), 1024); + oldDestDir[1024-1] = '\0'; - pNZBInfo->SetCategory(szCategory); - pNZBInfo->BuildDestDirName(); + nzbInfo->SetCategory(category); + nzbInfo->BuildDestDirName(); - bool bDirUnchanged = !strcmp(pNZBInfo->GetDestDir(), szOldDestDir); - bool bOK = bDirUnchanged || ArticleWriter::MoveCompletedFiles(pNZBInfo, szOldDestDir); + bool dirUnchanged = !strcmp(nzbInfo->GetDestDir(), oldDestDir); + bool ok = dirUnchanged || ArticleWriter::MoveCompletedFiles(nzbInfo, oldDestDir); - return bOK; + return ok; } -bool QueueCoordinator::SetQueueEntryName(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szName) +bool QueueCoordinator::SetQueueEntryName(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* name) { - if (pNZBInfo->GetPostInfo()) + if (nzbInfo->GetPostInfo()) { - error("Could not rename %s. File in post-process-stage", pNZBInfo->GetName()); + error("Could not rename %s. File in post-process-stage", nzbInfo->GetName()); return false; } - if (Util::EmptyStr(szName)) + if (Util::EmptyStr(name)) { - error("Could not rename %s. The new name cannot be empty", pNZBInfo->GetName()); + error("Could not rename %s. The new name cannot be empty", nzbInfo->GetName()); return false; } - char szNZBNicename[1024]; - NZBInfo::MakeNiceNZBName(szName, szNZBNicename, sizeof(szNZBNicename), false); - pNZBInfo->SetName(szNZBNicename); + char nzbNicename[1024]; + NZBInfo::MakeNiceNZBName(name, nzbNicename, sizeof(nzbNicename), false); + nzbInfo->SetName(nzbNicename); - if (pNZBInfo->GetKind() == NZBInfo::nkUrl) + if (nzbInfo->GetKind() == NZBInfo::nkUrl) { - char szFilename[1024]; - snprintf(szFilename, 1024, "%s.nzb", szNZBNicename); - szFilename[1024-1] = '\0'; - pNZBInfo->SetFilename(szFilename); + char filename[1024]; + snprintf(filename, 1024, "%s.nzb", nzbNicename); + filename[1024-1] = '\0'; + nzbInfo->SetFilename(filename); return true; } - char szOldDestDir[1024]; - strncpy(szOldDestDir, pNZBInfo->GetDestDir(), 1024); - szOldDestDir[1024-1] = '\0'; + char oldDestDir[1024]; + strncpy(oldDestDir, nzbInfo->GetDestDir(), 1024); + oldDestDir[1024-1] = '\0'; - pNZBInfo->BuildDestDirName(); + nzbInfo->BuildDestDirName(); - bool bDirUnchanged = !strcmp(pNZBInfo->GetDestDir(), szOldDestDir); - bool bOK = bDirUnchanged || ArticleWriter::MoveCompletedFiles(pNZBInfo, szOldDestDir); + bool dirUnchanged = !strcmp(nzbInfo->GetDestDir(), oldDestDir); + bool ok = dirUnchanged || ArticleWriter::MoveCompletedFiles(nzbInfo, oldDestDir); - return bOK; + return ok; } -bool QueueCoordinator::MergeQueueEntries(DownloadQueue* pDownloadQueue, NZBInfo* pDestNZBInfo, NZBInfo* pSrcNZBInfo) +bool QueueCoordinator::MergeQueueEntries(DownloadQueue* downloadQueue, NZBInfo* destNzbInfo, NZBInfo* srcNzbInfo) { - if (pDestNZBInfo->GetPostInfo() || pSrcNZBInfo->GetPostInfo()) + if (destNzbInfo->GetPostInfo() || srcNzbInfo->GetPostInfo()) { - error("Could not merge %s and %s. File in post-process-stage", pDestNZBInfo->GetName(), pSrcNZBInfo->GetName()); + error("Could not merge %s and %s. File in post-process-stage", destNzbInfo->GetName(), srcNzbInfo->GetName()); return false; } - if (pDestNZBInfo->GetKind() == NZBInfo::nkUrl || pSrcNZBInfo->GetKind() == NZBInfo::nkUrl) + if (destNzbInfo->GetKind() == NZBInfo::nkUrl || srcNzbInfo->GetKind() == NZBInfo::nkUrl) { - error("Could not merge %s and %s. URLs cannot be merged", pDestNZBInfo->GetName(), pSrcNZBInfo->GetName()); + error("Could not merge %s and %s. URLs cannot be merged", destNzbInfo->GetName(), srcNzbInfo->GetName()); return false; } // set new dest directory, new category and move downloaded files to new dest directory - pSrcNZBInfo->SetFilename(pSrcNZBInfo->GetFilename()); - SetQueueEntryCategory(pDownloadQueue, pSrcNZBInfo, pDestNZBInfo->GetCategory()); + srcNzbInfo->SetFilename(srcNzbInfo->GetFilename()); + SetQueueEntryCategory(downloadQueue, srcNzbInfo, destNzbInfo->GetCategory()); // reattach file items to new NZBInfo-object - for (FileList::iterator it = pSrcNZBInfo->GetFileList()->begin(); it != pSrcNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = srcNzbInfo->GetFileList()->begin(); it != srcNzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - pFileInfo->SetNZBInfo(pDestNZBInfo); - pDestNZBInfo->GetFileList()->push_back(pFileInfo); + FileInfo* fileInfo = *it; + fileInfo->SetNZBInfo(destNzbInfo); + destNzbInfo->GetFileList()->push_back(fileInfo); } - pSrcNZBInfo->GetFileList()->clear(); + srcNzbInfo->GetFileList()->clear(); - pDestNZBInfo->SetFileCount(pDestNZBInfo->GetFileCount() + pSrcNZBInfo->GetFileCount()); - pDestNZBInfo->SetActiveDownloads(pDestNZBInfo->GetActiveDownloads() + pSrcNZBInfo->GetActiveDownloads()); - pDestNZBInfo->SetFullContentHash(0); - pDestNZBInfo->SetFilteredContentHash(0); + destNzbInfo->SetFileCount(destNzbInfo->GetFileCount() + srcNzbInfo->GetFileCount()); + destNzbInfo->SetActiveDownloads(destNzbInfo->GetActiveDownloads() + srcNzbInfo->GetActiveDownloads()); + destNzbInfo->SetFullContentHash(0); + destNzbInfo->SetFilteredContentHash(0); - pDestNZBInfo->SetSize(pDestNZBInfo->GetSize() + pSrcNZBInfo->GetSize()); - pDestNZBInfo->SetRemainingSize(pDestNZBInfo->GetRemainingSize() + pSrcNZBInfo->GetRemainingSize()); - pDestNZBInfo->SetPausedFileCount(pDestNZBInfo->GetPausedFileCount() + pSrcNZBInfo->GetPausedFileCount()); - pDestNZBInfo->SetPausedSize(pDestNZBInfo->GetPausedSize() + pSrcNZBInfo->GetPausedSize()); + destNzbInfo->SetSize(destNzbInfo->GetSize() + srcNzbInfo->GetSize()); + destNzbInfo->SetRemainingSize(destNzbInfo->GetRemainingSize() + srcNzbInfo->GetRemainingSize()); + destNzbInfo->SetPausedFileCount(destNzbInfo->GetPausedFileCount() + srcNzbInfo->GetPausedFileCount()); + destNzbInfo->SetPausedSize(destNzbInfo->GetPausedSize() + srcNzbInfo->GetPausedSize()); - pDestNZBInfo->SetSuccessSize(pDestNZBInfo->GetSuccessSize() + pSrcNZBInfo->GetSuccessSize()); - pDestNZBInfo->SetCurrentSuccessSize(pDestNZBInfo->GetCurrentSuccessSize() + pSrcNZBInfo->GetCurrentSuccessSize()); - pDestNZBInfo->SetFailedSize(pDestNZBInfo->GetFailedSize() + pSrcNZBInfo->GetFailedSize()); - pDestNZBInfo->SetCurrentFailedSize(pDestNZBInfo->GetCurrentFailedSize() + pSrcNZBInfo->GetCurrentFailedSize()); + destNzbInfo->SetSuccessSize(destNzbInfo->GetSuccessSize() + srcNzbInfo->GetSuccessSize()); + destNzbInfo->SetCurrentSuccessSize(destNzbInfo->GetCurrentSuccessSize() + srcNzbInfo->GetCurrentSuccessSize()); + destNzbInfo->SetFailedSize(destNzbInfo->GetFailedSize() + srcNzbInfo->GetFailedSize()); + destNzbInfo->SetCurrentFailedSize(destNzbInfo->GetCurrentFailedSize() + srcNzbInfo->GetCurrentFailedSize()); - pDestNZBInfo->SetParSize(pDestNZBInfo->GetParSize() + pSrcNZBInfo->GetParSize()); - pDestNZBInfo->SetParSuccessSize(pDestNZBInfo->GetParSuccessSize() + pSrcNZBInfo->GetParSuccessSize()); - pDestNZBInfo->SetParCurrentSuccessSize(pDestNZBInfo->GetParCurrentSuccessSize() + pSrcNZBInfo->GetParCurrentSuccessSize()); - pDestNZBInfo->SetParFailedSize(pDestNZBInfo->GetParFailedSize() + pSrcNZBInfo->GetParFailedSize()); - pDestNZBInfo->SetParCurrentFailedSize(pDestNZBInfo->GetParCurrentFailedSize() + pSrcNZBInfo->GetParCurrentFailedSize()); - pDestNZBInfo->SetRemainingParCount(pDestNZBInfo->GetRemainingParCount() + pSrcNZBInfo->GetRemainingParCount()); + destNzbInfo->SetParSize(destNzbInfo->GetParSize() + srcNzbInfo->GetParSize()); + destNzbInfo->SetParSuccessSize(destNzbInfo->GetParSuccessSize() + srcNzbInfo->GetParSuccessSize()); + destNzbInfo->SetParCurrentSuccessSize(destNzbInfo->GetParCurrentSuccessSize() + srcNzbInfo->GetParCurrentSuccessSize()); + destNzbInfo->SetParFailedSize(destNzbInfo->GetParFailedSize() + srcNzbInfo->GetParFailedSize()); + destNzbInfo->SetParCurrentFailedSize(destNzbInfo->GetParCurrentFailedSize() + srcNzbInfo->GetParCurrentFailedSize()); + destNzbInfo->SetRemainingParCount(destNzbInfo->GetRemainingParCount() + srcNzbInfo->GetRemainingParCount()); - pDestNZBInfo->SetTotalArticles(pDestNZBInfo->GetTotalArticles() + pSrcNZBInfo->GetTotalArticles()); - pDestNZBInfo->SetSuccessArticles(pDestNZBInfo->GetSuccessArticles() + pSrcNZBInfo->GetSuccessArticles()); - pDestNZBInfo->SetFailedArticles(pDestNZBInfo->GetFailedArticles() + pSrcNZBInfo->GetFailedArticles()); - pDestNZBInfo->SetCurrentSuccessArticles(pDestNZBInfo->GetCurrentSuccessArticles() + pSrcNZBInfo->GetCurrentSuccessArticles()); - pDestNZBInfo->SetCurrentFailedArticles(pDestNZBInfo->GetCurrentFailedArticles() + pSrcNZBInfo->GetCurrentFailedArticles()); - pDestNZBInfo->GetServerStats()->ListOp(pSrcNZBInfo->GetServerStats(), ServerStatList::soAdd); - pDestNZBInfo->GetCurrentServerStats()->ListOp(pSrcNZBInfo->GetCurrentServerStats(), ServerStatList::soAdd); + destNzbInfo->SetTotalArticles(destNzbInfo->GetTotalArticles() + srcNzbInfo->GetTotalArticles()); + destNzbInfo->SetSuccessArticles(destNzbInfo->GetSuccessArticles() + srcNzbInfo->GetSuccessArticles()); + destNzbInfo->SetFailedArticles(destNzbInfo->GetFailedArticles() + srcNzbInfo->GetFailedArticles()); + destNzbInfo->SetCurrentSuccessArticles(destNzbInfo->GetCurrentSuccessArticles() + srcNzbInfo->GetCurrentSuccessArticles()); + destNzbInfo->SetCurrentFailedArticles(destNzbInfo->GetCurrentFailedArticles() + srcNzbInfo->GetCurrentFailedArticles()); + destNzbInfo->GetServerStats()->ListOp(srcNzbInfo->GetServerStats(), ServerStatList::soAdd); + destNzbInfo->GetCurrentServerStats()->ListOp(srcNzbInfo->GetCurrentServerStats(), ServerStatList::soAdd); - pDestNZBInfo->SetMinTime(pSrcNZBInfo->GetMinTime() < pDestNZBInfo->GetMinTime() ? pSrcNZBInfo->GetMinTime() : pDestNZBInfo->GetMinTime()); - pDestNZBInfo->SetMaxTime(pSrcNZBInfo->GetMaxTime() > pDestNZBInfo->GetMaxTime() ? pSrcNZBInfo->GetMaxTime() : pDestNZBInfo->GetMaxTime()); + destNzbInfo->SetMinTime(srcNzbInfo->GetMinTime() < destNzbInfo->GetMinTime() ? srcNzbInfo->GetMinTime() : destNzbInfo->GetMinTime()); + destNzbInfo->SetMaxTime(srcNzbInfo->GetMaxTime() > destNzbInfo->GetMaxTime() ? srcNzbInfo->GetMaxTime() : destNzbInfo->GetMaxTime()); - pDestNZBInfo->SetDownloadedSize(pDestNZBInfo->GetDownloadedSize() + pSrcNZBInfo->GetDownloadedSize()); - pDestNZBInfo->SetDownloadSec(pDestNZBInfo->GetDownloadSec() + pSrcNZBInfo->GetDownloadSec()); - pDestNZBInfo->SetDownloadStartTime((pDestNZBInfo->GetDownloadStartTime() > 0 && - pDestNZBInfo->GetDownloadStartTime() < pSrcNZBInfo->GetDownloadStartTime()) || pSrcNZBInfo->GetDownloadStartTime() == 0 ? - pDestNZBInfo->GetDownloadStartTime() : pSrcNZBInfo->GetDownloadStartTime()); + destNzbInfo->SetDownloadedSize(destNzbInfo->GetDownloadedSize() + srcNzbInfo->GetDownloadedSize()); + destNzbInfo->SetDownloadSec(destNzbInfo->GetDownloadSec() + srcNzbInfo->GetDownloadSec()); + destNzbInfo->SetDownloadStartTime((destNzbInfo->GetDownloadStartTime() > 0 && + destNzbInfo->GetDownloadStartTime() < srcNzbInfo->GetDownloadStartTime()) || srcNzbInfo->GetDownloadStartTime() == 0 ? + destNzbInfo->GetDownloadStartTime() : srcNzbInfo->GetDownloadStartTime()); // reattach completed file items to new NZBInfo-object - for (CompletedFiles::iterator it = pSrcNZBInfo->GetCompletedFiles()->begin(); it != pSrcNZBInfo->GetCompletedFiles()->end(); it++) + for (CompletedFiles::iterator it = srcNzbInfo->GetCompletedFiles()->begin(); it != srcNzbInfo->GetCompletedFiles()->end(); it++) { - CompletedFile* pCompletedFile = *it; - pDestNZBInfo->GetCompletedFiles()->push_back(pCompletedFile); + CompletedFile* completedFile = *it; + destNzbInfo->GetCompletedFiles()->push_back(completedFile); } - pSrcNZBInfo->GetCompletedFiles()->clear(); + srcNzbInfo->GetCompletedFiles()->clear(); // concatenate QueuedFilenames using character '|' as separator - int iLen = strlen(pDestNZBInfo->GetQueuedFilename()) + strlen(pSrcNZBInfo->GetQueuedFilename()) + 1; - char* szQueuedFilename = (char*)malloc(iLen); - snprintf(szQueuedFilename, iLen, "%s|%s", pDestNZBInfo->GetQueuedFilename(), pSrcNZBInfo->GetQueuedFilename()); - szQueuedFilename[iLen - 1] = '\0'; - pDestNZBInfo->SetQueuedFilename(szQueuedFilename); - free(szQueuedFilename); + int len = strlen(destNzbInfo->GetQueuedFilename()) + strlen(srcNzbInfo->GetQueuedFilename()) + 1; + char* queuedFilename = (char*)malloc(len); + snprintf(queuedFilename, len, "%s|%s", destNzbInfo->GetQueuedFilename(), srcNzbInfo->GetQueuedFilename()); + queuedFilename[len - 1] = '\0'; + destNzbInfo->SetQueuedFilename(queuedFilename); + free(queuedFilename); - pDownloadQueue->GetQueue()->Remove(pSrcNZBInfo); - g_pDiskState->DiscardFiles(pSrcNZBInfo); - delete pSrcNZBInfo; + downloadQueue->GetQueue()->Remove(srcNzbInfo); + g_pDiskState->DiscardFiles(srcNzbInfo); + delete srcNzbInfo; return true; } @@ -1165,117 +1165,117 @@ bool QueueCoordinator::MergeQueueEntries(DownloadQueue* pDownloadQueue, NZBInfo* * If any of file-items is being downloaded the command fail. * For each file-item an event "eaFileDeleted" is fired. */ -bool QueueCoordinator::SplitQueueEntries(DownloadQueue* pDownloadQueue, FileList* pFileList, const char* szName, NZBInfo** pNewNZBInfo) +bool QueueCoordinator::SplitQueueEntries(DownloadQueue* downloadQueue, FileList* fileList, const char* name, NZBInfo** newNzbInfo) { - if (pFileList->empty()) + if (fileList->empty()) { return false; } - NZBInfo* pSrcNZBInfo = NULL; + NZBInfo* srcNzbInfo = NULL; - for (FileList::iterator it = pFileList->begin(); it != pFileList->end(); it++) + for (FileList::iterator it = fileList->begin(); it != fileList->end(); it++) { - FileInfo* pFileInfo = *it; - if (pFileInfo->GetActiveDownloads() > 0 || pFileInfo->GetCompletedArticles() > 0) + FileInfo* fileInfo = *it; + if (fileInfo->GetActiveDownloads() > 0 || fileInfo->GetCompletedArticles() > 0) { - error("Could not split %s. File is already (partially) downloaded", pFileInfo->GetFilename()); + error("Could not split %s. File is already (partially) downloaded", fileInfo->GetFilename()); return false; } - if (pFileInfo->GetNZBInfo()->GetPostInfo()) + if (fileInfo->GetNZBInfo()->GetPostInfo()) { - error("Could not split %s. File in post-process-stage", pFileInfo->GetFilename()); + error("Could not split %s. File in post-process-stage", fileInfo->GetFilename()); return false; } - if (!pSrcNZBInfo) + if (!srcNzbInfo) { - pSrcNZBInfo = pFileInfo->GetNZBInfo(); + srcNzbInfo = fileInfo->GetNZBInfo(); } } - NZBInfo* pNZBInfo = new NZBInfo(); - pDownloadQueue->GetQueue()->push_back(pNZBInfo); + NZBInfo* nzbInfo = new NZBInfo(); + downloadQueue->GetQueue()->push_back(nzbInfo); - pNZBInfo->SetFilename(pSrcNZBInfo->GetFilename()); - pNZBInfo->SetName(szName); - pNZBInfo->SetCategory(pSrcNZBInfo->GetCategory()); - pNZBInfo->SetFullContentHash(0); - pNZBInfo->SetFilteredContentHash(0); - pNZBInfo->SetPriority(pSrcNZBInfo->GetPriority()); - pNZBInfo->BuildDestDirName(); - pNZBInfo->SetQueuedFilename(pSrcNZBInfo->GetQueuedFilename()); - pNZBInfo->GetParameters()->CopyFrom(pSrcNZBInfo->GetParameters()); + nzbInfo->SetFilename(srcNzbInfo->GetFilename()); + nzbInfo->SetName(name); + nzbInfo->SetCategory(srcNzbInfo->GetCategory()); + nzbInfo->SetFullContentHash(0); + nzbInfo->SetFilteredContentHash(0); + nzbInfo->SetPriority(srcNzbInfo->GetPriority()); + nzbInfo->BuildDestDirName(); + nzbInfo->SetQueuedFilename(srcNzbInfo->GetQueuedFilename()); + nzbInfo->GetParameters()->CopyFrom(srcNzbInfo->GetParameters()); - pSrcNZBInfo->SetFullContentHash(0); - pSrcNZBInfo->SetFilteredContentHash(0); + srcNzbInfo->SetFullContentHash(0); + srcNzbInfo->SetFilteredContentHash(0); - for (FileList::iterator it = pFileList->begin(); it != pFileList->end(); it++) + for (FileList::iterator it = fileList->begin(); it != fileList->end(); it++) { - FileInfo* pFileInfo = *it; + FileInfo* fileInfo = *it; - DownloadQueue::Aspect aspect = { DownloadQueue::eaFileDeleted, pDownloadQueue, pFileInfo->GetNZBInfo(), pFileInfo }; - pDownloadQueue->Notify(&aspect); + DownloadQueue::Aspect aspect = { DownloadQueue::eaFileDeleted, downloadQueue, fileInfo->GetNZBInfo(), fileInfo }; + downloadQueue->Notify(&aspect); - pFileInfo->SetNZBInfo(pNZBInfo); - pNZBInfo->GetFileList()->push_back(pFileInfo); - pSrcNZBInfo->GetFileList()->Remove(pFileInfo); + fileInfo->SetNZBInfo(nzbInfo); + nzbInfo->GetFileList()->push_back(fileInfo); + srcNzbInfo->GetFileList()->Remove(fileInfo); - pSrcNZBInfo->SetFileCount(pSrcNZBInfo->GetFileCount() - 1); - pSrcNZBInfo->SetSize(pSrcNZBInfo->GetSize() - pFileInfo->GetSize()); - pSrcNZBInfo->SetRemainingSize(pSrcNZBInfo->GetRemainingSize() - pFileInfo->GetRemainingSize()); - pSrcNZBInfo->SetCurrentSuccessSize(pSrcNZBInfo->GetCurrentSuccessSize() - pFileInfo->GetSuccessSize()); - pSrcNZBInfo->SetCurrentFailedSize(pSrcNZBInfo->GetCurrentFailedSize() - pFileInfo->GetFailedSize() - pFileInfo->GetMissedSize()); - pSrcNZBInfo->SetTotalArticles(pSrcNZBInfo->GetTotalArticles() - pFileInfo->GetTotalArticles()); - pSrcNZBInfo->SetCurrentSuccessArticles(pSrcNZBInfo->GetCurrentSuccessArticles() - pFileInfo->GetSuccessArticles()); - pSrcNZBInfo->SetCurrentFailedArticles(pSrcNZBInfo->GetCurrentFailedArticles() - pFileInfo->GetFailedArticles()); - pSrcNZBInfo->GetCurrentServerStats()->ListOp(pFileInfo->GetServerStats(), ServerStatList::soSubtract); + srcNzbInfo->SetFileCount(srcNzbInfo->GetFileCount() - 1); + srcNzbInfo->SetSize(srcNzbInfo->GetSize() - fileInfo->GetSize()); + srcNzbInfo->SetRemainingSize(srcNzbInfo->GetRemainingSize() - fileInfo->GetRemainingSize()); + srcNzbInfo->SetCurrentSuccessSize(srcNzbInfo->GetCurrentSuccessSize() - fileInfo->GetSuccessSize()); + srcNzbInfo->SetCurrentFailedSize(srcNzbInfo->GetCurrentFailedSize() - fileInfo->GetFailedSize() - fileInfo->GetMissedSize()); + srcNzbInfo->SetTotalArticles(srcNzbInfo->GetTotalArticles() - fileInfo->GetTotalArticles()); + srcNzbInfo->SetCurrentSuccessArticles(srcNzbInfo->GetCurrentSuccessArticles() - fileInfo->GetSuccessArticles()); + srcNzbInfo->SetCurrentFailedArticles(srcNzbInfo->GetCurrentFailedArticles() - fileInfo->GetFailedArticles()); + srcNzbInfo->GetCurrentServerStats()->ListOp(fileInfo->GetServerStats(), ServerStatList::soSubtract); - pNZBInfo->SetFileCount(pNZBInfo->GetFileCount() + 1); - pNZBInfo->SetSize(pNZBInfo->GetSize() + pFileInfo->GetSize()); - pNZBInfo->SetRemainingSize(pNZBInfo->GetRemainingSize() + pFileInfo->GetRemainingSize()); - pNZBInfo->SetCurrentSuccessSize(pNZBInfo->GetCurrentSuccessSize() + pFileInfo->GetSuccessSize()); - pNZBInfo->SetCurrentFailedSize(pNZBInfo->GetCurrentFailedSize() + pFileInfo->GetFailedSize() + pFileInfo->GetMissedSize()); - pNZBInfo->SetTotalArticles(pNZBInfo->GetTotalArticles() + pFileInfo->GetTotalArticles()); - pNZBInfo->SetCurrentSuccessArticles(pNZBInfo->GetCurrentSuccessArticles() + pFileInfo->GetSuccessArticles()); - pNZBInfo->SetCurrentFailedArticles(pNZBInfo->GetCurrentFailedArticles() + pFileInfo->GetFailedArticles()); - pNZBInfo->GetCurrentServerStats()->ListOp(pFileInfo->GetServerStats(), ServerStatList::soAdd); + nzbInfo->SetFileCount(nzbInfo->GetFileCount() + 1); + nzbInfo->SetSize(nzbInfo->GetSize() + fileInfo->GetSize()); + nzbInfo->SetRemainingSize(nzbInfo->GetRemainingSize() + fileInfo->GetRemainingSize()); + nzbInfo->SetCurrentSuccessSize(nzbInfo->GetCurrentSuccessSize() + fileInfo->GetSuccessSize()); + nzbInfo->SetCurrentFailedSize(nzbInfo->GetCurrentFailedSize() + fileInfo->GetFailedSize() + fileInfo->GetMissedSize()); + nzbInfo->SetTotalArticles(nzbInfo->GetTotalArticles() + fileInfo->GetTotalArticles()); + nzbInfo->SetCurrentSuccessArticles(nzbInfo->GetCurrentSuccessArticles() + fileInfo->GetSuccessArticles()); + nzbInfo->SetCurrentFailedArticles(nzbInfo->GetCurrentFailedArticles() + fileInfo->GetFailedArticles()); + nzbInfo->GetCurrentServerStats()->ListOp(fileInfo->GetServerStats(), ServerStatList::soAdd); - if (pFileInfo->GetParFile()) + if (fileInfo->GetParFile()) { - pSrcNZBInfo->SetParSize(pSrcNZBInfo->GetParSize() - pFileInfo->GetSize()); - pSrcNZBInfo->SetParCurrentSuccessSize(pSrcNZBInfo->GetParCurrentSuccessSize() - pFileInfo->GetSuccessSize()); - pSrcNZBInfo->SetParCurrentFailedSize(pSrcNZBInfo->GetParCurrentFailedSize() - pFileInfo->GetFailedSize() - pFileInfo->GetMissedSize()); - pSrcNZBInfo->SetRemainingParCount(pSrcNZBInfo->GetRemainingParCount() - 1); + srcNzbInfo->SetParSize(srcNzbInfo->GetParSize() - fileInfo->GetSize()); + srcNzbInfo->SetParCurrentSuccessSize(srcNzbInfo->GetParCurrentSuccessSize() - fileInfo->GetSuccessSize()); + srcNzbInfo->SetParCurrentFailedSize(srcNzbInfo->GetParCurrentFailedSize() - fileInfo->GetFailedSize() - fileInfo->GetMissedSize()); + srcNzbInfo->SetRemainingParCount(srcNzbInfo->GetRemainingParCount() - 1); - pNZBInfo->SetParSize(pNZBInfo->GetParSize() + pFileInfo->GetSize()); - pNZBInfo->SetParCurrentSuccessSize(pNZBInfo->GetParCurrentSuccessSize() + pFileInfo->GetSuccessSize()); - pNZBInfo->SetParCurrentFailedSize(pNZBInfo->GetParCurrentFailedSize() + pFileInfo->GetFailedSize() + pFileInfo->GetMissedSize()); - pNZBInfo->SetRemainingParCount(pNZBInfo->GetRemainingParCount() + 1); + nzbInfo->SetParSize(nzbInfo->GetParSize() + fileInfo->GetSize()); + nzbInfo->SetParCurrentSuccessSize(nzbInfo->GetParCurrentSuccessSize() + fileInfo->GetSuccessSize()); + nzbInfo->SetParCurrentFailedSize(nzbInfo->GetParCurrentFailedSize() + fileInfo->GetFailedSize() + fileInfo->GetMissedSize()); + nzbInfo->SetRemainingParCount(nzbInfo->GetRemainingParCount() + 1); } - if (pFileInfo->GetPaused()) + if (fileInfo->GetPaused()) { - pSrcNZBInfo->SetPausedFileCount(pSrcNZBInfo->GetPausedFileCount() - 1); - pSrcNZBInfo->SetPausedSize(pSrcNZBInfo->GetPausedSize() - pFileInfo->GetRemainingSize()); + srcNzbInfo->SetPausedFileCount(srcNzbInfo->GetPausedFileCount() - 1); + srcNzbInfo->SetPausedSize(srcNzbInfo->GetPausedSize() - fileInfo->GetRemainingSize()); - pNZBInfo->SetPausedFileCount(pSrcNZBInfo->GetPausedFileCount() + 1); - pNZBInfo->SetPausedSize(pNZBInfo->GetPausedSize() + pFileInfo->GetRemainingSize()); + nzbInfo->SetPausedFileCount(srcNzbInfo->GetPausedFileCount() + 1); + nzbInfo->SetPausedSize(nzbInfo->GetPausedSize() + fileInfo->GetRemainingSize()); } } - pNZBInfo->UpdateMinMaxTime(); - if (pSrcNZBInfo->GetCompletedFiles()->empty()) + nzbInfo->UpdateMinMaxTime(); + if (srcNzbInfo->GetCompletedFiles()->empty()) { - pSrcNZBInfo->UpdateMinMaxTime(); + srcNzbInfo->UpdateMinMaxTime(); } - if (pSrcNZBInfo->GetFileList()->empty()) + if (srcNzbInfo->GetFileList()->empty()) { - pDownloadQueue->GetQueue()->Remove(pSrcNZBInfo); - g_pDiskState->DiscardFiles(pSrcNZBInfo); - delete pSrcNZBInfo; + downloadQueue->GetQueue()->Remove(srcNzbInfo); + g_pDiskState->DiscardFiles(srcNzbInfo); + delete srcNzbInfo; } - *pNewNZBInfo = pNZBInfo; + *newNzbInfo = nzbInfo; return true; } diff --git a/daemon/queue/QueueCoordinator.h b/daemon/queue/QueueCoordinator.h index 9d57a870..6979ad2e 100644 --- a/daemon/queue/QueueCoordinator.h +++ b/daemon/queue/QueueCoordinator.h @@ -48,31 +48,31 @@ private: class CoordinatorDownloadQueue : public DownloadQueue { private: - QueueCoordinator* m_pOwner; - bool m_bMassEdit; - bool m_bWantSave; + QueueCoordinator* m_owner; + bool m_massEdit; + bool m_wantSave; friend class QueueCoordinator; public: - CoordinatorDownloadQueue(): m_bMassEdit(false), m_bWantSave(false) {} - virtual bool EditEntry(int ID, EEditAction eAction, int iOffset, const char* szText); - virtual bool EditList(IDList* pIDList, NameList* pNameList, EMatchMode eMatchMode, EEditAction eAction, int iOffset, const char* szText); + CoordinatorDownloadQueue(): m_massEdit(false), m_wantSave(false) {} + virtual bool EditEntry(int ID, EEditAction action, int offset, const char* text); + virtual bool EditList(IDList* idList, NameList* nameList, EMatchMode matchMode, EEditAction action, int offset, const char* text); virtual void Save(); }; private: - CoordinatorDownloadQueue m_DownloadQueue; - ActiveDownloads m_ActiveDownloads; - QueueEditor m_QueueEditor; - bool m_bHasMoreJobs; - int m_iDownloadsLimit; - int m_iServerConfigGeneration; + CoordinatorDownloadQueue m_downloadQueue; + ActiveDownloads m_activeDownloads; + QueueEditor m_queueEditor; + bool m_hasMoreJobs; + int m_downloadsLimit; + int m_serverConfigGeneration; - bool GetNextArticle(DownloadQueue* pDownloadQueue, FileInfo* &pFileInfo, ArticleInfo* &pArticleInfo); - void StartArticleDownload(FileInfo* pFileInfo, ArticleInfo* pArticleInfo, NNTPConnection* pConnection); - void ArticleCompleted(ArticleDownloader* pArticleDownloader); - void DeleteFileInfo(DownloadQueue* pDownloadQueue, FileInfo* pFileInfo, bool bCompleted); - void StatFileInfo(FileInfo* pFileInfo, bool bCompleted); - void CheckHealth(DownloadQueue* pDownloadQueue, FileInfo* pFileInfo); + bool GetNextArticle(DownloadQueue* downloadQueue, FileInfo* &fileInfo, ArticleInfo* &articleInfo); + void StartArticleDownload(FileInfo* fileInfo, ArticleInfo* articleInfo, NNTPConnection* connection); + void ArticleCompleted(ArticleDownloader* articleDownloader); + void DeleteFileInfo(DownloadQueue* downloadQueue, FileInfo* fileInfo, bool completed); + void StatFileInfo(FileInfo* fileInfo, bool completed); + void CheckHealth(DownloadQueue* downloadQueue, FileInfo* fileInfo); void ResetHangingDownloads(); void AdjustDownloadsLimit(); void Load(); @@ -89,15 +89,15 @@ public: void Update(Subject* Caller, void* Aspect); // editing queue - void AddNZBFileToQueue(NZBFile* pNZBFile, NZBInfo* pUrlInfo, bool bAddFirst); - void CheckDupeFileInfos(NZBInfo* pNZBInfo); - bool HasMoreJobs() { return m_bHasMoreJobs; } - void DiscardDiskFile(FileInfo* pFileInfo); - bool DeleteQueueEntry(DownloadQueue* pDownloadQueue, FileInfo* pFileInfo); - bool SetQueueEntryCategory(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szCategory); - bool SetQueueEntryName(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, const char* szName); - bool MergeQueueEntries(DownloadQueue* pDownloadQueue, NZBInfo* pDestNZBInfo, NZBInfo* pSrcNZBInfo); - bool SplitQueueEntries(DownloadQueue* pDownloadQueue, FileList* pFileList, const char* szName, NZBInfo** pNewNZBInfo); + void AddNZBFileToQueue(NZBFile* nzbFile, NZBInfo* urlInfo, bool addFirst); + void CheckDupeFileInfos(NZBInfo* nzbInfo); + bool HasMoreJobs() { return m_hasMoreJobs; } + void DiscardDiskFile(FileInfo* fileInfo); + bool DeleteQueueEntry(DownloadQueue* downloadQueue, FileInfo* fileInfo); + bool SetQueueEntryCategory(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* category); + bool SetQueueEntryName(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, const char* name); + bool MergeQueueEntries(DownloadQueue* downloadQueue, NZBInfo* destNzbInfo, NZBInfo* srcNzbInfo); + bool SplitQueueEntries(DownloadQueue* downloadQueue, FileList* fileList, const char* name, NZBInfo** newNzbInfo); }; extern QueueCoordinator* g_pQueueCoordinator; diff --git a/daemon/queue/QueueEditor.cpp b/daemon/queue/QueueEditor.cpp index 3f2e1eb9..3535947d 100644 --- a/daemon/queue/QueueEditor.cpp +++ b/daemon/queue/QueueEditor.cpp @@ -77,82 +77,82 @@ public: }; private: - NZBList* m_pNZBList; - QueueEditor::ItemList* m_pSortItemList; - ESortCriteria m_eSortCriteria; - ESortOrder m_eSortOrder; + NZBList* m_nzbList; + QueueEditor::ItemList* m_sortItemList; + ESortCriteria m_sortCriteria; + ESortOrder m_sortOrder; void AlignSelectedGroups(); public: - GroupSorter(NZBList* pNZBList, QueueEditor::ItemList* pSortItemList) : - m_pNZBList(pNZBList), m_pSortItemList(pSortItemList) {} - bool Execute(const char* szSort); - bool operator()(NZBInfo* pNZBInfo1, NZBInfo* pNZBInfo2) const; + GroupSorter(NZBList* nzbList, QueueEditor::ItemList* sortItemList) : + m_nzbList(nzbList), m_sortItemList(sortItemList) {} + bool Execute(const char* sort); + bool operator()(NZBInfo* nzbInfo1, NZBInfo* nzbInfo2) const; }; -bool GroupSorter::Execute(const char* szSort) +bool GroupSorter::Execute(const char* sort) { - if (!strcasecmp(szSort, "name") || !strcasecmp(szSort, "name+") || !strcasecmp(szSort, "name-")) + if (!strcasecmp(sort, "name") || !strcasecmp(sort, "name+") || !strcasecmp(sort, "name-")) { - m_eSortCriteria = scName; + m_sortCriteria = scName; } - else if (!strcasecmp(szSort, "size") || !strcasecmp(szSort, "size+") || !strcasecmp(szSort, "size-")) + else if (!strcasecmp(sort, "size") || !strcasecmp(sort, "size+") || !strcasecmp(sort, "size-")) { - m_eSortCriteria = scSize; + m_sortCriteria = scSize; } - else if (!strcasecmp(szSort, "left") || !strcasecmp(szSort, "left+") || !strcasecmp(szSort, "left-")) + else if (!strcasecmp(sort, "left") || !strcasecmp(sort, "left+") || !strcasecmp(sort, "left-")) { - m_eSortCriteria = scRemainingSize; + m_sortCriteria = scRemainingSize; } - else if (!strcasecmp(szSort, "age") || !strcasecmp(szSort, "age+") || !strcasecmp(szSort, "age-")) + else if (!strcasecmp(sort, "age") || !strcasecmp(sort, "age+") || !strcasecmp(sort, "age-")) { - m_eSortCriteria = scAge; + m_sortCriteria = scAge; } - else if (!strcasecmp(szSort, "category") || !strcasecmp(szSort, "category+") || !strcasecmp(szSort, "category-")) + else if (!strcasecmp(sort, "category") || !strcasecmp(sort, "category+") || !strcasecmp(sort, "category-")) { - m_eSortCriteria = scCategory; + m_sortCriteria = scCategory; } - else if (!strcasecmp(szSort, "priority") || !strcasecmp(szSort, "priority+") || !strcasecmp(szSort, "priority-")) + else if (!strcasecmp(sort, "priority") || !strcasecmp(sort, "priority+") || !strcasecmp(sort, "priority-")) { - m_eSortCriteria = scPriority; + m_sortCriteria = scPriority; } else { - error("Could not sort groups: incorrect sort order (%s)", szSort); + error("Could not sort groups: incorrect sort order (%s)", sort); return false; } - char lastCh = szSort[strlen(szSort) - 1]; + char lastCh = sort[strlen(sort) - 1]; if (lastCh == '+') { - m_eSortOrder = soAscending; + m_sortOrder = soAscending; } else if (lastCh == '-') { - m_eSortOrder = soDescending; + m_sortOrder = soDescending; } else { - m_eSortOrder = soAuto; + m_sortOrder = soAuto; } AlignSelectedGroups(); - NZBList tempList = *m_pNZBList; + NZBList tempList = *m_nzbList; - ESortOrder eOrigSortOrder = m_eSortOrder; - if (m_eSortOrder == soAuto && m_eSortCriteria == scPriority) + ESortOrder origSortOrder = m_sortOrder; + if (m_sortOrder == soAuto && m_sortCriteria == scPriority) { - m_eSortOrder = soDescending; + m_sortOrder = soDescending; } - std::sort(m_pNZBList->begin(), m_pNZBList->end(), *this); + std::sort(m_nzbList->begin(), m_nzbList->end(), *this); - if (eOrigSortOrder == soAuto && tempList == *m_pNZBList) + if (origSortOrder == soAuto && tempList == *m_nzbList) { - m_eSortOrder = m_eSortOrder == soDescending ? soAscending : soDescending; - std::sort(m_pNZBList->begin(), m_pNZBList->end(), *this); + m_sortOrder = m_sortOrder == soDescending ? soAscending : soDescending; + std::sort(m_nzbList->begin(), m_nzbList->end(), *this); } tempList.clear(); // prevent destroying of elements @@ -160,56 +160,56 @@ bool GroupSorter::Execute(const char* szSort) return true; } -bool GroupSorter::operator()(NZBInfo* pNZBInfo1, NZBInfo* pNZBInfo2) const +bool GroupSorter::operator()(NZBInfo* nzbInfo1, NZBInfo* nzbInfo2) const { // if list of ID is empty - sort all items - bool bSortItem1 = m_pSortItemList->empty(); - bool bSortItem2 = m_pSortItemList->empty(); + bool sortItem1 = m_sortItemList->empty(); + bool sortItem2 = m_sortItemList->empty(); - for (QueueEditor::ItemList::iterator it = m_pSortItemList->begin(); it != m_pSortItemList->end(); it++) + for (QueueEditor::ItemList::iterator it = m_sortItemList->begin(); it != m_sortItemList->end(); it++) { - QueueEditor::EditItem* pItem = *it; - bSortItem1 |= pItem->m_pNZBInfo == pNZBInfo1; - bSortItem2 |= pItem->m_pNZBInfo == pNZBInfo2; + QueueEditor::EditItem* item = *it; + sortItem1 |= item->m_nzbInfo == nzbInfo1; + sortItem2 |= item->m_nzbInfo == nzbInfo2; } - if (!bSortItem1 || !bSortItem2) + if (!sortItem1 || !sortItem2) { return false; } bool ret = false; - if (m_eSortOrder == soDescending) + if (m_sortOrder == soDescending) { - std::swap(pNZBInfo1, pNZBInfo2); + std::swap(nzbInfo1, nzbInfo2); } - switch (m_eSortCriteria) + switch (m_sortCriteria) { case scName: - ret = strcmp(pNZBInfo1->GetName(), pNZBInfo2->GetName()) < 0; + ret = strcmp(nzbInfo1->GetName(), nzbInfo2->GetName()) < 0; break; case scSize: - ret = pNZBInfo1->GetSize() < pNZBInfo2->GetSize(); + ret = nzbInfo1->GetSize() < nzbInfo2->GetSize(); break; case scRemainingSize: - ret = pNZBInfo1->GetRemainingSize() - pNZBInfo1->GetPausedSize() < - pNZBInfo2->GetRemainingSize() - pNZBInfo2->GetPausedSize(); + ret = nzbInfo1->GetRemainingSize() - nzbInfo1->GetPausedSize() < + nzbInfo2->GetRemainingSize() - nzbInfo2->GetPausedSize(); break; case scAge: - ret = pNZBInfo1->GetMinTime() > pNZBInfo2->GetMinTime(); + ret = nzbInfo1->GetMinTime() > nzbInfo2->GetMinTime(); break; case scCategory: - ret = strcmp(pNZBInfo1->GetCategory(), pNZBInfo2->GetCategory()) < 0; + ret = strcmp(nzbInfo1->GetCategory(), nzbInfo2->GetCategory()) < 0; break; case scPriority: - ret = pNZBInfo1->GetPriority() < pNZBInfo2->GetPriority(); + ret = nzbInfo1->GetPriority() < nzbInfo2->GetPriority(); break; } @@ -218,48 +218,48 @@ bool GroupSorter::operator()(NZBInfo* pNZBInfo1, NZBInfo* pNZBInfo2) const void GroupSorter::AlignSelectedGroups() { - NZBInfo* pLastNZBInfo = NULL; - unsigned int iLastNum = 0; - unsigned int iNum = 0; - while (iNum < m_pNZBList->size()) + NZBInfo* lastNzbInfo = NULL; + unsigned int lastNum = 0; + unsigned int num = 0; + while (num < m_nzbList->size()) { - NZBInfo* pNZBInfo = m_pNZBList->at(iNum); + NZBInfo* nzbInfo = m_nzbList->at(num); - bool bSelected = false; - for (QueueEditor::ItemList::iterator it = m_pSortItemList->begin(); it != m_pSortItemList->end(); it++) + bool selected = false; + for (QueueEditor::ItemList::iterator it = m_sortItemList->begin(); it != m_sortItemList->end(); it++) { - QueueEditor::EditItem* pItem = *it; - if (pItem->m_pNZBInfo == pNZBInfo) + QueueEditor::EditItem* item = *it; + if (item->m_nzbInfo == nzbInfo) { - bSelected = true; + selected = true; break; } } - if (bSelected) + if (selected) { - if (pLastNZBInfo && iNum - iLastNum > 1) + if (lastNzbInfo && num - lastNum > 1) { - m_pNZBList->erase(m_pNZBList->begin() + iNum); - m_pNZBList->insert(m_pNZBList->begin() + iLastNum + 1, pNZBInfo); - iLastNum++; + m_nzbList->erase(m_nzbList->begin() + num); + m_nzbList->insert(m_nzbList->begin() + lastNum + 1, nzbInfo); + lastNum++; } else { - iLastNum = iNum; + lastNum = num; } - pLastNZBInfo = pNZBInfo; + lastNzbInfo = nzbInfo; } - iNum++; + num++; } } -QueueEditor::EditItem::EditItem(FileInfo* pFileInfo, NZBInfo* pNZBInfo, int iOffset) +QueueEditor::EditItem::EditItem(FileInfo* fileInfo, NZBInfo* nzbInfo, int offset) { - m_pFileInfo = pFileInfo; - m_pNZBInfo = pNZBInfo; - m_iOffset = iOffset; + m_fileInfo = fileInfo; + m_nzbInfo = nzbInfo; + m_offset = offset; } QueueEditor::QueueEditor() @@ -272,17 +272,17 @@ QueueEditor::~QueueEditor() debug("Destroying QueueEditor"); } -FileInfo* QueueEditor::FindFileInfo(int iID) +FileInfo* QueueEditor::FindFileInfo(int id) { - for (NZBList::iterator it = m_pDownloadQueue->GetQueue()->begin(); it != m_pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = m_downloadQueue->GetQueue()->begin(); it != m_downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - if (pFileInfo->GetID() == iID) + FileInfo* fileInfo = *it2; + if (fileInfo->GetID() == id) { - return pFileInfo; + return fileInfo; } } } @@ -292,233 +292,233 @@ FileInfo* QueueEditor::FindFileInfo(int iID) /* * Set the pause flag of the specific entry in the queue */ -void QueueEditor::PauseUnpauseEntry(FileInfo* pFileInfo, bool bPause) +void QueueEditor::PauseUnpauseEntry(FileInfo* fileInfo, bool pause) { - pFileInfo->SetPaused(bPause); + fileInfo->SetPaused(pause); } /* * Removes entry */ -void QueueEditor::DeleteEntry(FileInfo* pFileInfo) +void QueueEditor::DeleteEntry(FileInfo* fileInfo) { - pFileInfo->GetNZBInfo()->PrintMessage( - pFileInfo->GetNZBInfo()->GetDeleting() ? Message::mkDetail : Message::mkInfo, - "Deleting file %s from download queue", pFileInfo->GetFilename()); - g_pQueueCoordinator->DeleteQueueEntry(m_pDownloadQueue, pFileInfo); + fileInfo->GetNZBInfo()->PrintMessage( + fileInfo->GetNZBInfo()->GetDeleting() ? Message::mkDetail : Message::mkInfo, + "Deleting file %s from download queue", fileInfo->GetFilename()); + g_pQueueCoordinator->DeleteQueueEntry(m_downloadQueue, fileInfo); } /* * Moves entry in the queue */ -void QueueEditor::MoveEntry(FileInfo* pFileInfo, int iOffset) +void QueueEditor::MoveEntry(FileInfo* fileInfo, int offset) { - int iEntry = 0; - for (FileList::iterator it = pFileInfo->GetNZBInfo()->GetFileList()->begin(); it != pFileInfo->GetNZBInfo()->GetFileList()->end(); it++) + int entry = 0; + for (FileList::iterator it = fileInfo->GetNZBInfo()->GetFileList()->begin(); it != fileInfo->GetNZBInfo()->GetFileList()->end(); it++) { - FileInfo* pFileInfo2 = *it; - if (pFileInfo2 == pFileInfo) + FileInfo* fileInfo2 = *it; + if (fileInfo2 == fileInfo) { break; } - iEntry ++; + entry ++; } - int iNewEntry = iEntry + iOffset; - int iSize = (int)pFileInfo->GetNZBInfo()->GetFileList()->size(); + int newEntry = entry + offset; + int size = (int)fileInfo->GetNZBInfo()->GetFileList()->size(); - if (iNewEntry < 0) + if (newEntry < 0) { - iNewEntry = 0; + newEntry = 0; } - if (iNewEntry > iSize - 1) + if (newEntry > size - 1) { - iNewEntry = (int)iSize - 1; + newEntry = (int)size - 1; } - if (iNewEntry >= 0 && iNewEntry <= iSize - 1) + if (newEntry >= 0 && newEntry <= size - 1) { - pFileInfo->GetNZBInfo()->GetFileList()->erase(pFileInfo->GetNZBInfo()->GetFileList()->begin() + iEntry); - pFileInfo->GetNZBInfo()->GetFileList()->insert(pFileInfo->GetNZBInfo()->GetFileList()->begin() + iNewEntry, pFileInfo); + fileInfo->GetNZBInfo()->GetFileList()->erase(fileInfo->GetNZBInfo()->GetFileList()->begin() + entry); + fileInfo->GetNZBInfo()->GetFileList()->insert(fileInfo->GetNZBInfo()->GetFileList()->begin() + newEntry, fileInfo); } } /* * Moves group in the queue */ -void QueueEditor::MoveGroup(NZBInfo* pNZBInfo, int iOffset) +void QueueEditor::MoveGroup(NZBInfo* nzbInfo, int offset) { - int iEntry = 0; - for (NZBList::iterator it = m_pDownloadQueue->GetQueue()->begin(); it != m_pDownloadQueue->GetQueue()->end(); it++) + int entry = 0; + for (NZBList::iterator it = m_downloadQueue->GetQueue()->begin(); it != m_downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo2 = *it; - if (pNZBInfo2 == pNZBInfo) + NZBInfo* nzbInfo2 = *it; + if (nzbInfo2 == nzbInfo) { break; } - iEntry ++; + entry ++; } - int iNewEntry = iEntry + iOffset; - int iSize = (int)m_pDownloadQueue->GetQueue()->size(); + int newEntry = entry + offset; + int size = (int)m_downloadQueue->GetQueue()->size(); - if (iNewEntry < 0) + if (newEntry < 0) { - iNewEntry = 0; + newEntry = 0; } - if (iNewEntry > iSize - 1) + if (newEntry > size - 1) { - iNewEntry = (int)iSize - 1; + newEntry = (int)size - 1; } - if (iNewEntry >= 0 && iNewEntry <= iSize - 1) + if (newEntry >= 0 && newEntry <= size - 1) { - m_pDownloadQueue->GetQueue()->erase(m_pDownloadQueue->GetQueue()->begin() + iEntry); - m_pDownloadQueue->GetQueue()->insert(m_pDownloadQueue->GetQueue()->begin() + iNewEntry, pNZBInfo); + m_downloadQueue->GetQueue()->erase(m_downloadQueue->GetQueue()->begin() + entry); + m_downloadQueue->GetQueue()->insert(m_downloadQueue->GetQueue()->begin() + newEntry, nzbInfo); } } -bool QueueEditor::EditEntry(DownloadQueue* pDownloadQueue, int ID, DownloadQueue::EEditAction eAction, int iOffset, const char* szText) +bool QueueEditor::EditEntry(DownloadQueue* downloadQueue, int ID, DownloadQueue::EEditAction action, int offset, const char* text) { - m_pDownloadQueue = pDownloadQueue; + m_downloadQueue = downloadQueue; IDList cIDList; cIDList.push_back(ID); - return InternEditList(NULL, &cIDList, eAction, iOffset, szText); + return InternEditList(NULL, &cIDList, action, offset, text); } -bool QueueEditor::EditList(DownloadQueue* pDownloadQueue, IDList* pIDList, NameList* pNameList, DownloadQueue::EMatchMode eMatchMode, - DownloadQueue::EEditAction eAction, int iOffset, const char* szText) +bool QueueEditor::EditList(DownloadQueue* downloadQueue, IDList* idList, NameList* nameList, DownloadQueue::EMatchMode matchMode, + DownloadQueue::EEditAction action, int offset, const char* text) { - if (eAction == DownloadQueue::eaPostDelete) + if (action == DownloadQueue::eaPostDelete) { - return g_pPrePostProcessor->EditList(pDownloadQueue, pIDList, eAction, iOffset, szText); + return g_pPrePostProcessor->EditList(downloadQueue, idList, action, offset, text); } - else if (DownloadQueue::eaHistoryDelete <= eAction && eAction <= DownloadQueue::eaHistorySetName) + else if (DownloadQueue::eaHistoryDelete <= action && action <= DownloadQueue::eaHistorySetName) { - return g_pHistoryCoordinator->EditList(pDownloadQueue, pIDList, eAction, iOffset, szText); + return g_pHistoryCoordinator->EditList(downloadQueue, idList, action, offset, text); } - m_pDownloadQueue = pDownloadQueue; - bool bOK = true; + m_downloadQueue = downloadQueue; + bool ok = true; - if (pNameList) + if (nameList) { - pIDList = new IDList(); - bOK = BuildIDListFromNameList(pIDList, pNameList, eMatchMode, eAction); + idList = new IDList(); + ok = BuildIDListFromNameList(idList, nameList, matchMode, action); } - bOK = bOK && (InternEditList(NULL, pIDList, eAction, iOffset, szText) || eMatchMode == DownloadQueue::mmRegEx); + ok = ok && (InternEditList(NULL, idList, action, offset, text) || matchMode == DownloadQueue::mmRegEx); - m_pDownloadQueue->Save(); + m_downloadQueue->Save(); - if (pNameList) + if (nameList) { - delete pIDList; + delete idList; } - return bOK; + return ok; } -bool QueueEditor::InternEditList(ItemList* pItemList, - IDList* pIDList, DownloadQueue::EEditAction eAction, int iOffset, const char* szText) +bool QueueEditor::InternEditList(ItemList* itemList, + IDList* idList, DownloadQueue::EEditAction action, int offset, const char* text) { - ItemList itemList; - if (!pItemList) + ItemList workItems; + if (!itemList) { - pItemList = &itemList; - PrepareList(pItemList, pIDList, eAction, iOffset); + itemList = &workItems; + PrepareList(itemList, idList, action, offset); } - switch (eAction) + switch (action) { case DownloadQueue::eaFilePauseAllPars: case DownloadQueue::eaFilePauseExtraPars: - PauseParsInGroups(pItemList, eAction == DownloadQueue::eaFilePauseExtraPars); + PauseParsInGroups(itemList, action == DownloadQueue::eaFilePauseExtraPars); break; case DownloadQueue::eaGroupMerge: - return MergeGroups(pItemList); + return MergeGroups(itemList); case DownloadQueue::eaGroupSort: - return SortGroups(pItemList, szText); + return SortGroups(itemList, text); case DownloadQueue::eaFileSplit: - return SplitGroup(pItemList, szText); + return SplitGroup(itemList, text); case DownloadQueue::eaFileReorder: - ReorderFiles(pItemList); + ReorderFiles(itemList); break; default: - for (ItemList::iterator it = pItemList->begin(); it != pItemList->end(); it++) + for (ItemList::iterator it = itemList->begin(); it != itemList->end(); it++) { - EditItem* pItem = *it; - switch (eAction) + EditItem* item = *it; + switch (action) { case DownloadQueue::eaFilePause: - PauseUnpauseEntry(pItem->m_pFileInfo, true); + PauseUnpauseEntry(item->m_fileInfo, true); break; case DownloadQueue::eaFileResume: - PauseUnpauseEntry(pItem->m_pFileInfo, false); + PauseUnpauseEntry(item->m_fileInfo, false); break; case DownloadQueue::eaFileMoveOffset: case DownloadQueue::eaFileMoveTop: case DownloadQueue::eaFileMoveBottom: - MoveEntry(pItem->m_pFileInfo, pItem->m_iOffset); + MoveEntry(item->m_fileInfo, item->m_offset); break; case DownloadQueue::eaFileDelete: - DeleteEntry(pItem->m_pFileInfo); + DeleteEntry(item->m_fileInfo); break; case DownloadQueue::eaGroupSetPriority: - SetNZBPriority(pItem->m_pNZBInfo, szText); + SetNZBPriority(item->m_nzbInfo, text); break; case DownloadQueue::eaGroupSetCategory: case DownloadQueue::eaGroupApplyCategory: - SetNZBCategory(pItem->m_pNZBInfo, szText, eAction == DownloadQueue::eaGroupApplyCategory); + SetNZBCategory(item->m_nzbInfo, text, action == DownloadQueue::eaGroupApplyCategory); break; case DownloadQueue::eaGroupSetName: - SetNZBName(pItem->m_pNZBInfo, szText); + SetNZBName(item->m_nzbInfo, text); break; case DownloadQueue::eaGroupSetDupeKey: case DownloadQueue::eaGroupSetDupeScore: case DownloadQueue::eaGroupSetDupeMode: - SetNZBDupeParam(pItem->m_pNZBInfo, eAction, szText); + SetNZBDupeParam(item->m_nzbInfo, action, text); break; case DownloadQueue::eaGroupSetParameter: - SetNZBParameter(pItem->m_pNZBInfo, szText); + SetNZBParameter(item->m_nzbInfo, text); break; case DownloadQueue::eaGroupMoveTop: case DownloadQueue::eaGroupMoveBottom: case DownloadQueue::eaGroupMoveOffset: - MoveGroup(pItem->m_pNZBInfo, pItem->m_iOffset); + MoveGroup(item->m_nzbInfo, item->m_offset); break; case DownloadQueue::eaGroupPause: case DownloadQueue::eaGroupResume: case DownloadQueue::eaGroupPauseAllPars: case DownloadQueue::eaGroupPauseExtraPars: - EditGroup(pItem->m_pNZBInfo, eAction, iOffset, szText); + EditGroup(item->m_nzbInfo, action, offset, text); break; case DownloadQueue::eaGroupDelete: case DownloadQueue::eaGroupDupeDelete: case DownloadQueue::eaGroupFinalDelete: - if (pItem->m_pNZBInfo->GetKind() == NZBInfo::nkUrl) + if (item->m_nzbInfo->GetKind() == NZBInfo::nkUrl) { - DeleteUrl(pItem->m_pNZBInfo, eAction); + DeleteUrl(item->m_nzbInfo, action); } else { - EditGroup(pItem->m_pNZBInfo, eAction, iOffset, szText); + EditGroup(item->m_nzbInfo, action, offset, text); } @@ -526,172 +526,172 @@ bool QueueEditor::InternEditList(ItemList* pItemList, // suppress compiler warning "enumeration not handled in switch" break; } - delete pItem; + delete item; } } - return pItemList->size() > 0; + return itemList->size() > 0; } -void QueueEditor::PrepareList(ItemList* pItemList, IDList* pIDList, - DownloadQueue::EEditAction eAction, int iOffset) +void QueueEditor::PrepareList(ItemList* itemList, IDList* idList, + DownloadQueue::EEditAction action, int offset) { - if (eAction == DownloadQueue::eaFileMoveTop || eAction == DownloadQueue::eaGroupMoveTop) + if (action == DownloadQueue::eaFileMoveTop || action == DownloadQueue::eaGroupMoveTop) { - iOffset = -MAX_ID; + offset = -MAX_ID; } - else if (eAction == DownloadQueue::eaFileMoveBottom || eAction == DownloadQueue::eaGroupMoveBottom) + else if (action == DownloadQueue::eaFileMoveBottom || action == DownloadQueue::eaGroupMoveBottom) { - iOffset = MAX_ID; + offset = MAX_ID; } - pItemList->reserve(pIDList->size()); - if ((iOffset != 0) && - (eAction == DownloadQueue::eaFileMoveOffset || eAction == DownloadQueue::eaFileMoveTop || eAction == DownloadQueue::eaFileMoveBottom)) + itemList->reserve(idList->size()); + if ((offset != 0) && + (action == DownloadQueue::eaFileMoveOffset || action == DownloadQueue::eaFileMoveTop || action == DownloadQueue::eaFileMoveBottom)) { // add IDs to list in order they currently have in download queue - for (NZBList::iterator it = m_pDownloadQueue->GetQueue()->begin(); it != m_pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = m_downloadQueue->GetQueue()->begin(); it != m_downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - int iNrEntries = (int)pNZBInfo->GetFileList()->size(); - int iLastDestPos = -1; - int iStart, iEnd, iStep; - if (iOffset < 0) + NZBInfo* nzbInfo = *it; + int nrEntries = (int)nzbInfo->GetFileList()->size(); + int lastDestPos = -1; + int start, end, step; + if (offset < 0) { - iStart = 0; - iEnd = iNrEntries; - iStep = 1; + start = 0; + end = nrEntries; + step = 1; } else { - iStart = iNrEntries - 1; - iEnd = -1; - iStep = -1; + start = nrEntries - 1; + end = -1; + step = -1; } - for (int iIndex = iStart; iIndex != iEnd; iIndex += iStep) + for (int index = start; index != end; index += step) { - FileInfo* pFileInfo = pNZBInfo->GetFileList()->at(iIndex); - IDList::iterator it2 = std::find(pIDList->begin(), pIDList->end(), pFileInfo->GetID()); - if (it2 != pIDList->end()) + FileInfo* fileInfo = nzbInfo->GetFileList()->at(index); + IDList::iterator it2 = std::find(idList->begin(), idList->end(), fileInfo->GetID()); + if (it2 != idList->end()) { - int iWorkOffset = iOffset; - int iDestPos = iIndex + iWorkOffset; - if (iLastDestPos == -1) + int workOffset = offset; + int destPos = index + workOffset; + if (lastDestPos == -1) { - if (iDestPos < 0) + if (destPos < 0) { - iWorkOffset = -iIndex; + workOffset = -index; } - else if (iDestPos > iNrEntries - 1) + else if (destPos > nrEntries - 1) { - iWorkOffset = iNrEntries - 1 - iIndex; + workOffset = nrEntries - 1 - index; } } else { - if (iWorkOffset < 0 && iDestPos <= iLastDestPos) + if (workOffset < 0 && destPos <= lastDestPos) { - iWorkOffset = iLastDestPos - iIndex + 1; + workOffset = lastDestPos - index + 1; } - else if (iWorkOffset > 0 && iDestPos >= iLastDestPos) + else if (workOffset > 0 && destPos >= lastDestPos) { - iWorkOffset = iLastDestPos - iIndex - 1; + workOffset = lastDestPos - index - 1; } } - iLastDestPos = iIndex + iWorkOffset; - pItemList->push_back(new EditItem(pFileInfo, NULL, iWorkOffset)); + lastDestPos = index + workOffset; + itemList->push_back(new EditItem(fileInfo, NULL, workOffset)); } } } } - else if ((iOffset != 0) && - (eAction == DownloadQueue::eaGroupMoveOffset || eAction == DownloadQueue::eaGroupMoveTop || eAction == DownloadQueue::eaGroupMoveBottom)) + else if ((offset != 0) && + (action == DownloadQueue::eaGroupMoveOffset || action == DownloadQueue::eaGroupMoveTop || action == DownloadQueue::eaGroupMoveBottom)) { // add IDs to list in order they currently have in download queue // per group only one FileInfo is added to the list - int iNrEntries = (int)m_pDownloadQueue->GetQueue()->size(); - int iLastDestPos = -1; - int iStart, iEnd, iStep; - if (iOffset < 0) + int nrEntries = (int)m_downloadQueue->GetQueue()->size(); + int lastDestPos = -1; + int start, end, step; + if (offset < 0) { - iStart = 0; - iEnd = iNrEntries; - iStep = 1; + start = 0; + end = nrEntries; + step = 1; } else { - iStart = iNrEntries - 1; - iEnd = -1; - iStep = -1; + start = nrEntries - 1; + end = -1; + step = -1; } - for (int iIndex = iStart; iIndex != iEnd; iIndex += iStep) + for (int index = start; index != end; index += step) { - NZBInfo* pNZBInfo = m_pDownloadQueue->GetQueue()->at(iIndex); - IDList::iterator it2 = std::find(pIDList->begin(), pIDList->end(), pNZBInfo->GetID()); - if (it2 != pIDList->end()) + NZBInfo* nzbInfo = m_downloadQueue->GetQueue()->at(index); + IDList::iterator it2 = std::find(idList->begin(), idList->end(), nzbInfo->GetID()); + if (it2 != idList->end()) { - int iWorkOffset = iOffset; - int iDestPos = iIndex + iWorkOffset; - if (iLastDestPos == -1) + int workOffset = offset; + int destPos = index + workOffset; + if (lastDestPos == -1) { - if (iDestPos < 0) + if (destPos < 0) { - iWorkOffset = -iIndex; + workOffset = -index; } - else if (iDestPos > iNrEntries - 1) + else if (destPos > nrEntries - 1) { - iWorkOffset = iNrEntries - 1 - iIndex; + workOffset = nrEntries - 1 - index; } } else { - if (iWorkOffset < 0 && iDestPos <= iLastDestPos) + if (workOffset < 0 && destPos <= lastDestPos) { - iWorkOffset = iLastDestPos - iIndex + 1; + workOffset = lastDestPos - index + 1; } - else if (iWorkOffset > 0 && iDestPos >= iLastDestPos) + else if (workOffset > 0 && destPos >= lastDestPos) { - iWorkOffset = iLastDestPos - iIndex - 1; + workOffset = lastDestPos - index - 1; } } - iLastDestPos = iIndex + iWorkOffset; - pItemList->push_back(new EditItem(NULL, pNZBInfo, iWorkOffset)); + lastDestPos = index + workOffset; + itemList->push_back(new EditItem(NULL, nzbInfo, workOffset)); } } } - else if (eAction < DownloadQueue::eaGroupMoveOffset) + else if (action < DownloadQueue::eaGroupMoveOffset) { // check ID range - int iMaxID = 0; - int iMinID = MAX_ID; - for (NZBList::iterator it = m_pDownloadQueue->GetQueue()->begin(); it != m_pDownloadQueue->GetQueue()->end(); it++) + int maxId = 0; + int minId = MAX_ID; + for (NZBList::iterator it = m_downloadQueue->GetQueue()->begin(); it != m_downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - int ID = pFileInfo->GetID(); - if (ID > iMaxID) + FileInfo* fileInfo = *it2; + int ID = fileInfo->GetID(); + if (ID > maxId) { - iMaxID = ID; + maxId = ID; } - if (ID < iMinID) + if (ID < minId) { - iMinID = ID; + minId = ID; } } } //add IDs to list in order they were transmitted in command - for (IDList::iterator it = pIDList->begin(); it != pIDList->end(); it++) + for (IDList::iterator it = idList->begin(); it != idList->end(); it++) { - int iID = *it; - if (iMinID <= iID && iID <= iMaxID) + int id = *it; + if (minId <= id && id <= maxId) { - FileInfo* pFileInfo = FindFileInfo(iID); - if (pFileInfo) + FileInfo* fileInfo = FindFileInfo(id); + if (fileInfo) { - pItemList->push_back(new EditItem(pFileInfo, NULL, iOffset)); + itemList->push_back(new EditItem(fileInfo, NULL, offset)); } } } @@ -699,34 +699,34 @@ void QueueEditor::PrepareList(ItemList* pItemList, IDList* pIDList, else { // check ID range - int iMaxID = 0; - int iMinID = MAX_ID; - for (NZBList::iterator it = m_pDownloadQueue->GetQueue()->begin(); it != m_pDownloadQueue->GetQueue()->end(); it++) + int maxId = 0; + int minId = MAX_ID; + for (NZBList::iterator it = m_downloadQueue->GetQueue()->begin(); it != m_downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - int ID = pNZBInfo->GetID(); - if (ID > iMaxID) + NZBInfo* nzbInfo = *it; + int ID = nzbInfo->GetID(); + if (ID > maxId) { - iMaxID = ID; + maxId = ID; } - if (ID < iMinID) + if (ID < minId) { - iMinID = ID; + minId = ID; } } //add IDs to list in order they were transmitted in command - for (IDList::iterator it = pIDList->begin(); it != pIDList->end(); it++) + for (IDList::iterator it = idList->begin(); it != idList->end(); it++) { - int iID = *it; - if (iMinID <= iID && iID <= iMaxID) + int id = *it; + if (minId <= id && id <= maxId) { - for (NZBList::iterator it2 = m_pDownloadQueue->GetQueue()->begin(); it2 != m_pDownloadQueue->GetQueue()->end(); it2++) + for (NZBList::iterator it2 = m_downloadQueue->GetQueue()->begin(); it2 != m_downloadQueue->GetQueue()->end(); it2++) { - NZBInfo* pNZBInfo = *it2; - if (iID == pNZBInfo->GetID()) + NZBInfo* nzbInfo = *it2; + if (id == nzbInfo->GetID()) { - pItemList->push_back(new EditItem(NULL, pNZBInfo, iOffset)); + itemList->push_back(new EditItem(NULL, nzbInfo, offset)); } } } @@ -734,10 +734,10 @@ void QueueEditor::PrepareList(ItemList* pItemList, IDList* pIDList, } } -bool QueueEditor::BuildIDListFromNameList(IDList* pIDList, NameList* pNameList, DownloadQueue::EMatchMode eMatchMode, DownloadQueue::EEditAction eAction) +bool QueueEditor::BuildIDListFromNameList(IDList* idList, NameList* nameList, DownloadQueue::EMatchMode matchMode, DownloadQueue::EEditAction action) { #ifndef HAVE_REGEX_H - if (eMatchMode == mmRegEx) + if (matchMode == mmRegEx) { return false; } @@ -745,62 +745,62 @@ bool QueueEditor::BuildIDListFromNameList(IDList* pIDList, NameList* pNameList, std::set uniqueIDs; - for (NameList::iterator it = pNameList->begin(); it != pNameList->end(); it++) + for (NameList::iterator it = nameList->begin(); it != nameList->end(); it++) { - const char* szName = *it; + const char* name = *it; - RegEx *pRegEx = NULL; - if (eMatchMode == DownloadQueue::mmRegEx) + RegEx *regEx = NULL; + if (matchMode == DownloadQueue::mmRegEx) { - pRegEx = new RegEx(szName); - if (!pRegEx->IsValid()) + regEx = new RegEx(name); + if (!regEx->IsValid()) { - delete pRegEx; + delete regEx; return false; } } - bool bFound = false; + bool found = false; - for (NZBList::iterator it3 = m_pDownloadQueue->GetQueue()->begin(); it3 != m_pDownloadQueue->GetQueue()->end(); it3++) + for (NZBList::iterator it3 = m_downloadQueue->GetQueue()->begin(); it3 != m_downloadQueue->GetQueue()->end(); it3++) { - NZBInfo* pNZBInfo = *it3; + NZBInfo* nzbInfo = *it3; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - if (eAction < DownloadQueue::eaGroupMoveOffset) + FileInfo* fileInfo = *it2; + if (action < DownloadQueue::eaGroupMoveOffset) { // file action - char szFilename[MAX_PATH]; - snprintf(szFilename, sizeof(szFilename) - 1, "%s/%s", pFileInfo->GetNZBInfo()->GetName(), Util::BaseFileName(pFileInfo->GetFilename())); - if (((!pRegEx && !strcmp(szFilename, szName)) || (pRegEx && pRegEx->Match(szFilename))) && - (uniqueIDs.find(pFileInfo->GetID()) == uniqueIDs.end())) + char filename[MAX_PATH]; + snprintf(filename, sizeof(filename) - 1, "%s/%s", fileInfo->GetNZBInfo()->GetName(), Util::BaseFileName(fileInfo->GetFilename())); + if (((!regEx && !strcmp(filename, name)) || (regEx && regEx->Match(filename))) && + (uniqueIDs.find(fileInfo->GetID()) == uniqueIDs.end())) { - uniqueIDs.insert(pFileInfo->GetID()); - pIDList->push_back(pFileInfo->GetID()); - bFound = true; + uniqueIDs.insert(fileInfo->GetID()); + idList->push_back(fileInfo->GetID()); + found = true; } } } - if (eAction >= DownloadQueue::eaGroupMoveOffset) + if (action >= DownloadQueue::eaGroupMoveOffset) { // group action - const char *szFilename = pNZBInfo->GetName(); - if (((!pRegEx && !strcmp(szFilename, szName)) || (pRegEx && pRegEx->Match(szFilename))) && - (uniqueIDs.find(pNZBInfo->GetID()) == uniqueIDs.end())) + const char *filename = nzbInfo->GetName(); + if (((!regEx && !strcmp(filename, name)) || (regEx && regEx->Match(filename))) && + (uniqueIDs.find(nzbInfo->GetID()) == uniqueIDs.end())) { - uniqueIDs.insert(pNZBInfo->GetID()); - pIDList->push_back(pNZBInfo->GetID()); - bFound = true; + uniqueIDs.insert(nzbInfo->GetID()); + idList->push_back(nzbInfo->GetID()); + found = true; } } } - delete pRegEx; + delete regEx; - if (!bFound && (eMatchMode == DownloadQueue::mmName)) + if (!found && (matchMode == DownloadQueue::mmName)) { return false; } @@ -809,30 +809,30 @@ bool QueueEditor::BuildIDListFromNameList(IDList* pIDList, NameList* pNameList, return true; } -bool QueueEditor::EditGroup(NZBInfo* pNZBInfo, DownloadQueue::EEditAction eAction, int iOffset, const char* szText) +bool QueueEditor::EditGroup(NZBInfo* nzbInfo, DownloadQueue::EEditAction action, int offset, const char* text) { ItemList itemList; - bool bAllPaused = true; - int iID = pNZBInfo->GetID(); + bool allPaused = true; + int id = nzbInfo->GetID(); // collecting files belonging to group - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - itemList.push_back(new EditItem(pFileInfo, NULL, 0)); - bAllPaused &= pFileInfo->GetPaused(); + FileInfo* fileInfo = *it; + itemList.push_back(new EditItem(fileInfo, NULL, 0)); + allPaused &= fileInfo->GetPaused(); } - if (eAction == DownloadQueue::eaGroupDelete || eAction == DownloadQueue::eaGroupDupeDelete || eAction == DownloadQueue::eaGroupFinalDelete) + if (action == DownloadQueue::eaGroupDelete || action == DownloadQueue::eaGroupDupeDelete || action == DownloadQueue::eaGroupFinalDelete) { - pNZBInfo->SetDeleting(true); - pNZBInfo->SetAvoidHistory(eAction == DownloadQueue::eaGroupFinalDelete); - pNZBInfo->SetDeletePaused(bAllPaused); - if (eAction == DownloadQueue::eaGroupDupeDelete) + nzbInfo->SetDeleting(true); + nzbInfo->SetAvoidHistory(action == DownloadQueue::eaGroupFinalDelete); + nzbInfo->SetDeletePaused(allPaused); + if (action == DownloadQueue::eaGroupDupeDelete) { - pNZBInfo->SetDeleteStatus(NZBInfo::dsDupe); + nzbInfo->SetDeleteStatus(NZBInfo::dsDupe); } - pNZBInfo->SetCleanupDisk(CanCleanupDisk(pNZBInfo)); + nzbInfo->SetCleanupDisk(CanCleanupDisk(nzbInfo)); } DownloadQueue::EEditAction GroupToFileMap[] = { @@ -862,40 +862,40 @@ bool QueueEditor::EditGroup(NZBInfo* pNZBInfo, DownloadQueue::EEditAction eActio (DownloadQueue::EEditAction)0, (DownloadQueue::EEditAction)0 }; - bool bOK = InternEditList(&itemList, NULL, GroupToFileMap[eAction], iOffset, szText); + bool ok = InternEditList(&itemList, NULL, GroupToFileMap[action], offset, text); - if ((eAction == DownloadQueue::eaGroupDelete || eAction == DownloadQueue::eaGroupDupeDelete || eAction == DownloadQueue::eaGroupFinalDelete) && + if ((action == DownloadQueue::eaGroupDelete || action == DownloadQueue::eaGroupDupeDelete || action == DownloadQueue::eaGroupFinalDelete) && // NZBInfo could have been destroyed already - m_pDownloadQueue->GetQueue()->Find(iID)) + m_downloadQueue->GetQueue()->Find(id)) { - DownloadQueue::Aspect deleteAspect = { DownloadQueue::eaNzbDeleted, m_pDownloadQueue, pNZBInfo, NULL }; - m_pDownloadQueue->Notify(&deleteAspect); + DownloadQueue::Aspect deleteAspect = { DownloadQueue::eaNzbDeleted, m_downloadQueue, nzbInfo, NULL }; + m_downloadQueue->Notify(&deleteAspect); } - return bOK; + return ok; } -void QueueEditor::PauseParsInGroups(ItemList* pItemList, bool bExtraParsOnly) +void QueueEditor::PauseParsInGroups(ItemList* itemList, bool extraParsOnly) { while (true) { FileList GroupFileList; - FileInfo* pFirstFileInfo = NULL; + FileInfo* firstFileInfo = NULL; - for (ItemList::iterator it = pItemList->begin(); it != pItemList->end(); ) + for (ItemList::iterator it = itemList->begin(); it != itemList->end(); ) { - EditItem* pItem = *it; - if (!pFirstFileInfo || - (pFirstFileInfo->GetNZBInfo() == pItem->m_pFileInfo->GetNZBInfo())) + EditItem* item = *it; + if (!firstFileInfo || + (firstFileInfo->GetNZBInfo() == item->m_fileInfo->GetNZBInfo())) { - GroupFileList.push_back(pItem->m_pFileInfo); - if (!pFirstFileInfo) + GroupFileList.push_back(item->m_fileInfo); + if (!firstFileInfo) { - pFirstFileInfo = pItem->m_pFileInfo; + firstFileInfo = item->m_fileInfo; } - delete pItem; - pItemList->erase(it); - it = pItemList->begin(); + delete item; + itemList->erase(it); + it = itemList->begin(); continue; } it++; @@ -903,7 +903,7 @@ void QueueEditor::PauseParsInGroups(ItemList* pItemList, bool bExtraParsOnly) if (!GroupFileList.empty()) { - PausePars(&GroupFileList, bExtraParsOnly); + PausePars(&GroupFileList, extraParsOnly); } else { @@ -920,178 +920,178 @@ void QueueEditor::PauseParsInGroups(ItemList* pItemList, bool bExtraParsOnly) * In a case, if there are no just-pars, but only vols, we find the smallest vol-file * and do not affect it, but pause all other pars. */ -void QueueEditor::PausePars(FileList* pFileList, bool bExtraParsOnly) +void QueueEditor::PausePars(FileList* fileList, bool extraParsOnly) { debug("QueueEditor: Pausing pars"); FileList Pars, Vols; - for (FileList::iterator it = pFileList->begin(); it != pFileList->end(); it++) + for (FileList::iterator it = fileList->begin(); it != fileList->end(); it++) { - FileInfo* pFileInfo = *it; - char szLoFileName[1024]; - strncpy(szLoFileName, pFileInfo->GetFilename(), 1024); - szLoFileName[1024-1] = '\0'; - for (char* p = szLoFileName; *p; p++) *p = tolower(*p); // convert string to lowercase + FileInfo* fileInfo = *it; + char loFileName[1024]; + strncpy(loFileName, fileInfo->GetFilename(), 1024); + loFileName[1024-1] = '\0'; + for (char* p = loFileName; *p; p++) *p = tolower(*p); // convert string to lowercase - if (strstr(szLoFileName, ".par2")) + if (strstr(loFileName, ".par2")) { - if (!bExtraParsOnly) + if (!extraParsOnly) { - pFileInfo->SetPaused(true); + fileInfo->SetPaused(true); } else { - if (strstr(szLoFileName, ".vol")) + if (strstr(loFileName, ".vol")) { - Vols.push_back(pFileInfo); + Vols.push_back(fileInfo); } else { - Pars.push_back(pFileInfo); + Pars.push_back(fileInfo); } } } } - if (bExtraParsOnly) + if (extraParsOnly) { if (!Pars.empty()) { for (FileList::iterator it = Vols.begin(); it != Vols.end(); it++) { - FileInfo* pFileInfo = *it; - pFileInfo->SetPaused(true); + FileInfo* fileInfo = *it; + fileInfo->SetPaused(true); } } else { // pausing all Vol-files except the smallest one - FileInfo* pSmallest = NULL; + FileInfo* smallest = NULL; for (FileList::iterator it = Vols.begin(); it != Vols.end(); it++) { - FileInfo* pFileInfo = *it; - if (!pSmallest) + FileInfo* fileInfo = *it; + if (!smallest) { - pSmallest = pFileInfo; + smallest = fileInfo; } - else if (pSmallest->GetSize() > pFileInfo->GetSize()) + else if (smallest->GetSize() > fileInfo->GetSize()) { - pSmallest->SetPaused(true); - pSmallest = pFileInfo; + smallest->SetPaused(true); + smallest = fileInfo; } else { - pFileInfo->SetPaused(true); + fileInfo->SetPaused(true); } } } } } -void QueueEditor::SetNZBPriority(NZBInfo* pNZBInfo, const char* szPriority) +void QueueEditor::SetNZBPriority(NZBInfo* nzbInfo, const char* priority) { - debug("Setting priority %s for %s", szPriority, pNZBInfo->GetName()); + debug("Setting priority %s for %s", priority, nzbInfo->GetName()); - int iPriority = atoi(szPriority); - pNZBInfo->SetPriority(iPriority); + int priorityVal = atoi(priority); + nzbInfo->SetPriority(priorityVal); } -void QueueEditor::SetNZBCategory(NZBInfo* pNZBInfo, const char* szCategory, bool bApplyParams) +void QueueEditor::SetNZBCategory(NZBInfo* nzbInfo, const char* category, bool applyParams) { - debug("QueueEditor: setting category '%s' for '%s'", szCategory, pNZBInfo->GetName()); + debug("QueueEditor: setting category '%s' for '%s'", category, nzbInfo->GetName()); - bool bOldUnpack = g_pOptions->GetUnpack(); - const char* szOldPostScript = g_pOptions->GetPostScript(); - if (bApplyParams && !Util::EmptyStr(pNZBInfo->GetCategory())) + bool oldUnpack = g_pOptions->GetUnpack(); + const char* oldPostScript = g_pOptions->GetPostScript(); + if (applyParams && !Util::EmptyStr(nzbInfo->GetCategory())) { - Options::Category* pCategory = g_pOptions->FindCategory(pNZBInfo->GetCategory(), false); - if (pCategory) + Options::Category* categoryObj = g_pOptions->FindCategory(nzbInfo->GetCategory(), false); + if (categoryObj) { - bOldUnpack = pCategory->GetUnpack(); - if (!Util::EmptyStr(pCategory->GetPostScript())) + oldUnpack = categoryObj->GetUnpack(); + if (!Util::EmptyStr(categoryObj->GetPostScript())) { - szOldPostScript = pCategory->GetPostScript(); + oldPostScript = categoryObj->GetPostScript(); } } } - g_pQueueCoordinator->SetQueueEntryCategory(m_pDownloadQueue, pNZBInfo, szCategory); + g_pQueueCoordinator->SetQueueEntryCategory(m_downloadQueue, nzbInfo, category); - if (!bApplyParams) + if (!applyParams) { return; } - bool bNewUnpack = g_pOptions->GetUnpack(); - const char* szNewPostScript = g_pOptions->GetPostScript(); - if (!Util::EmptyStr(pNZBInfo->GetCategory())) + bool newUnpack = g_pOptions->GetUnpack(); + const char* newPostScript = g_pOptions->GetPostScript(); + if (!Util::EmptyStr(nzbInfo->GetCategory())) { - Options::Category* pCategory = g_pOptions->FindCategory(pNZBInfo->GetCategory(), false); - if (pCategory) + Options::Category* categoryObj = g_pOptions->FindCategory(nzbInfo->GetCategory(), false); + if (categoryObj) { - bNewUnpack = pCategory->GetUnpack(); - if (!Util::EmptyStr(pCategory->GetPostScript())) + newUnpack = categoryObj->GetUnpack(); + if (!Util::EmptyStr(categoryObj->GetPostScript())) { - szNewPostScript = pCategory->GetPostScript(); + newPostScript = categoryObj->GetPostScript(); } } } - if (bOldUnpack != bNewUnpack) + if (oldUnpack != newUnpack) { - pNZBInfo->GetParameters()->SetParameter("*Unpack:", bNewUnpack ? "yes" : "no"); + nzbInfo->GetParameters()->SetParameter("*Unpack:", newUnpack ? "yes" : "no"); } - if (strcasecmp(szOldPostScript, szNewPostScript)) + if (strcasecmp(oldPostScript, newPostScript)) { // add new params not existed in old category - Tokenizer tokNew(szNewPostScript, ",;"); - while (const char* szNewScriptName = tokNew.Next()) + Tokenizer tokNew(newPostScript, ",;"); + while (const char* newScriptName = tokNew.Next()) { - bool bFound = false; - const char* szOldScriptName; - Tokenizer tokOld(szOldPostScript, ",;"); - while ((szOldScriptName = tokOld.Next()) && !bFound) + bool found = false; + const char* oldScriptName; + Tokenizer tokOld(oldPostScript, ",;"); + while ((oldScriptName = tokOld.Next()) && !found) { - bFound = !strcasecmp(szNewScriptName, szOldScriptName); + found = !strcasecmp(newScriptName, oldScriptName); } - if (!bFound) + if (!found) { - char szParam[1024]; - snprintf(szParam, 1024, "%s:", szNewScriptName); - szParam[1024-1] = '\0'; - pNZBInfo->GetParameters()->SetParameter(szParam, "yes"); + char param[1024]; + snprintf(param, 1024, "%s:", newScriptName); + param[1024-1] = '\0'; + nzbInfo->GetParameters()->SetParameter(param, "yes"); } } // remove old params not existed in new category - Tokenizer tokOld(szOldPostScript, ",;"); - while (const char* szOldScriptName = tokOld.Next()) + Tokenizer tokOld(oldPostScript, ",;"); + while (const char* oldScriptName = tokOld.Next()) { - bool bFound = false; - const char* szNewScriptName; - Tokenizer tokNew(szNewPostScript, ",;"); - while ((szNewScriptName = tokNew.Next()) && !bFound) + bool found = false; + const char* newScriptName; + Tokenizer tokNew(newPostScript, ",;"); + while ((newScriptName = tokNew.Next()) && !found) { - bFound = !strcasecmp(szNewScriptName, szOldScriptName); + found = !strcasecmp(newScriptName, oldScriptName); } - if (!bFound) + if (!found) { - char szParam[1024]; - snprintf(szParam, 1024, "%s:", szOldScriptName); - szParam[1024-1] = '\0'; - pNZBInfo->GetParameters()->SetParameter(szParam, "no"); + char param[1024]; + snprintf(param, 1024, "%s:", oldScriptName); + param[1024-1] = '\0'; + nzbInfo->GetParameters()->SetParameter(param, "no"); } } } } -void QueueEditor::SetNZBName(NZBInfo* pNZBInfo, const char* szName) +void QueueEditor::SetNZBName(NZBInfo* nzbInfo, const char* name) { - debug("QueueEditor: renaming '%s' to '%s'", pNZBInfo->GetName(), szName); + debug("QueueEditor: renaming '%s' to '%s'", nzbInfo->GetName(), name); - g_pQueueCoordinator->SetQueueEntryName(m_pDownloadQueue, pNZBInfo, szName); + g_pQueueCoordinator->SetQueueEntryName(m_downloadQueue, nzbInfo, name); } /** @@ -1099,22 +1099,22 @@ void QueueEditor::SetNZBName(NZBInfo* pNZBInfo, const char* szName) * The deletion is most always possible, except the case if all remaining files in queue * (belonging to this nzb-file) are PARS. */ -bool QueueEditor::CanCleanupDisk(NZBInfo* pNZBInfo) +bool QueueEditor::CanCleanupDisk(NZBInfo* nzbInfo) { - if (pNZBInfo->GetDeleteStatus() != NZBInfo::dsNone) + if (nzbInfo->GetDeleteStatus() != NZBInfo::dsNone) { return true; } - for (FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - char szLoFileName[1024]; - strncpy(szLoFileName, pFileInfo->GetFilename(), 1024); - szLoFileName[1024-1] = '\0'; - for (char* p = szLoFileName; *p; p++) *p = tolower(*p); // convert string to lowercase + FileInfo* fileInfo = *it; + char loFileName[1024]; + strncpy(loFileName, fileInfo->GetFilename(), 1024); + loFileName[1024-1] = '\0'; + for (char* p = loFileName; *p; p++) *p = tolower(*p); // convert string to lowercase - if (!strstr(szLoFileName, ".par2")) + if (!strstr(loFileName, ".par2")) { // non-par file found return true; @@ -1124,149 +1124,149 @@ bool QueueEditor::CanCleanupDisk(NZBInfo* pNZBInfo) return false; } -bool QueueEditor::MergeGroups(ItemList* pItemList) +bool QueueEditor::MergeGroups(ItemList* itemList) { - if (pItemList->size() == 0) + if (itemList->size() == 0) { return false; } - bool bOK = true; + bool ok = true; - EditItem* pDestItem = pItemList->front(); + EditItem* destItem = itemList->front(); - for (ItemList::iterator it = pItemList->begin() + 1; it != pItemList->end(); it++) + for (ItemList::iterator it = itemList->begin() + 1; it != itemList->end(); it++) { - EditItem* pItem = *it; - if (pItem->m_pNZBInfo != pDestItem->m_pNZBInfo) + EditItem* item = *it; + if (item->m_nzbInfo != destItem->m_nzbInfo) { - debug("merge %s to %s", pItem->m_pNZBInfo->GetFilename(), pDestItem->m_pNZBInfo->GetFilename()); - if (g_pQueueCoordinator->MergeQueueEntries(m_pDownloadQueue, pDestItem->m_pNZBInfo, pItem->m_pNZBInfo)) + debug("merge %s to %s", item->m_nzbInfo->GetFilename(), destItem->m_nzbInfo->GetFilename()); + if (g_pQueueCoordinator->MergeQueueEntries(m_downloadQueue, destItem->m_nzbInfo, item->m_nzbInfo)) { - bOK = false; + ok = false; } } - delete pItem; + delete item; } - delete pDestItem; - return bOK; + delete destItem; + return ok; } -bool QueueEditor::SplitGroup(ItemList* pItemList, const char* szName) +bool QueueEditor::SplitGroup(ItemList* itemList, const char* name) { - if (pItemList->size() == 0) + if (itemList->size() == 0) { return false; } FileList fileList(false); - for (ItemList::iterator it = pItemList->begin(); it != pItemList->end(); it++) + for (ItemList::iterator it = itemList->begin(); it != itemList->end(); it++) { - EditItem* pItem = *it; - fileList.push_back(pItem->m_pFileInfo); - delete pItem; + EditItem* item = *it; + fileList.push_back(item->m_fileInfo); + delete item; } - NZBInfo* pNewNZBInfo = NULL; - bool bOK = g_pQueueCoordinator->SplitQueueEntries(m_pDownloadQueue, &fileList, szName, &pNewNZBInfo); + NZBInfo* newNzbInfo = NULL; + bool ok = g_pQueueCoordinator->SplitQueueEntries(m_downloadQueue, &fileList, name, &newNzbInfo); - return bOK; + return ok; } -bool QueueEditor::SortGroups(ItemList* pItemList, const char* szSort) +bool QueueEditor::SortGroups(ItemList* itemList, const char* sort) { - GroupSorter sorter(m_pDownloadQueue->GetQueue(), pItemList); - return sorter.Execute(szSort); + GroupSorter sorter(m_downloadQueue->GetQueue(), itemList); + return sorter.Execute(sort); } -void QueueEditor::ReorderFiles(ItemList* pItemList) +void QueueEditor::ReorderFiles(ItemList* itemList) { - if (pItemList->size() == 0) + if (itemList->size() == 0) { return; } - EditItem* pFirstItem = pItemList->front(); - NZBInfo* pNZBInfo = pFirstItem->m_pFileInfo->GetNZBInfo(); - unsigned int iInsertPos = 0; + EditItem* firstItem = itemList->front(); + NZBInfo* nzbInfo = firstItem->m_fileInfo->GetNZBInfo(); + unsigned int insertPos = 0; // now can reorder - for (ItemList::iterator it = pItemList->begin(); it != pItemList->end(); it++) + for (ItemList::iterator it = itemList->begin(); it != itemList->end(); it++) { - EditItem* pItem = *it; - FileInfo* pFileInfo = pItem->m_pFileInfo; + EditItem* item = *it; + FileInfo* fileInfo = item->m_fileInfo; // move file item - FileList::iterator it2 = std::find(pNZBInfo->GetFileList()->begin(), pNZBInfo->GetFileList()->end(), pFileInfo); - if (it2 != pNZBInfo->GetFileList()->end()) + FileList::iterator it2 = std::find(nzbInfo->GetFileList()->begin(), nzbInfo->GetFileList()->end(), fileInfo); + if (it2 != nzbInfo->GetFileList()->end()) { - pNZBInfo->GetFileList()->erase(it2); - pNZBInfo->GetFileList()->insert(pNZBInfo->GetFileList()->begin() + iInsertPos, pFileInfo); - iInsertPos++; + nzbInfo->GetFileList()->erase(it2); + nzbInfo->GetFileList()->insert(nzbInfo->GetFileList()->begin() + insertPos, fileInfo); + insertPos++; } - delete pItem; + delete item; } } -void QueueEditor::SetNZBParameter(NZBInfo* pNZBInfo, const char* szParamString) +void QueueEditor::SetNZBParameter(NZBInfo* nzbInfo, const char* paramString) { - debug("QueueEditor: setting nzb parameter '%s' for '%s'", szParamString, Util::BaseFileName(pNZBInfo->GetFilename())); + debug("QueueEditor: setting nzb parameter '%s' for '%s'", paramString, Util::BaseFileName(nzbInfo->GetFilename())); - char* szStr = strdup(szParamString); + char* str = strdup(paramString); - char* szValue = strchr(szStr, '='); - if (szValue) + char* value = strchr(str, '='); + if (value) { - *szValue = '\0'; - szValue++; - pNZBInfo->GetParameters()->SetParameter(szStr, szValue); + *value = '\0'; + value++; + nzbInfo->GetParameters()->SetParameter(str, value); } else { - error("Could not set nzb parameter for %s: invalid argument: %s", pNZBInfo->GetName(), szParamString); + error("Could not set nzb parameter for %s: invalid argument: %s", nzbInfo->GetName(), paramString); } - free(szStr); + free(str); } -void QueueEditor::SetNZBDupeParam(NZBInfo* pNZBInfo, DownloadQueue::EEditAction eAction, const char* szText) +void QueueEditor::SetNZBDupeParam(NZBInfo* nzbInfo, DownloadQueue::EEditAction action, const char* text) { - debug("QueueEditor: setting dupe parameter %i='%s' for '%s'", (int)eAction, szText, pNZBInfo->GetName()); + debug("QueueEditor: setting dupe parameter %i='%s' for '%s'", (int)action, text, nzbInfo->GetName()); - switch (eAction) + switch (action) { case DownloadQueue::eaGroupSetDupeKey: - pNZBInfo->SetDupeKey(szText); + nzbInfo->SetDupeKey(text); break; case DownloadQueue::eaGroupSetDupeScore: - pNZBInfo->SetDupeScore(atoi(szText)); + nzbInfo->SetDupeScore(atoi(text)); break; case DownloadQueue::eaGroupSetDupeMode: { - EDupeMode eMode = dmScore; - if (!strcasecmp(szText, "SCORE")) + EDupeMode mode = dmScore; + if (!strcasecmp(text, "SCORE")) { - eMode = dmScore; + mode = dmScore; } - else if (!strcasecmp(szText, "ALL")) + else if (!strcasecmp(text, "ALL")) { - eMode = dmAll; + mode = dmAll; } - else if (!strcasecmp(szText, "FORCE")) + else if (!strcasecmp(text, "FORCE")) { - eMode = dmForce; + mode = dmForce; } else { - error("Could not set duplicate mode for %s: incorrect mode (%s)", pNZBInfo->GetName(), szText); + error("Could not set duplicate mode for %s: incorrect mode (%s)", nzbInfo->GetName(), text); return; } - pNZBInfo->SetDupeMode(eMode); + nzbInfo->SetDupeMode(mode); break; } @@ -1276,7 +1276,7 @@ void QueueEditor::SetNZBDupeParam(NZBInfo* pNZBInfo, DownloadQueue::EEditAction } } -bool QueueEditor::DeleteUrl(NZBInfo* pNZBInfo, DownloadQueue::EEditAction eAction) +bool QueueEditor::DeleteUrl(NZBInfo* nzbInfo, DownloadQueue::EEditAction action) { - return g_pUrlCoordinator->DeleteQueueEntry(m_pDownloadQueue, pNZBInfo, eAction == DownloadQueue::eaGroupFinalDelete); + return g_pUrlCoordinator->DeleteQueueEntry(m_downloadQueue, nzbInfo, action == DownloadQueue::eaGroupFinalDelete); } diff --git a/daemon/queue/QueueEditor.h b/daemon/queue/QueueEditor.h index 40f4feca..fb3cedc0 100644 --- a/daemon/queue/QueueEditor.h +++ b/daemon/queue/QueueEditor.h @@ -36,47 +36,47 @@ public: class EditItem { public: - int m_iOffset; - FileInfo* m_pFileInfo; - NZBInfo* m_pNZBInfo; + int m_offset; + FileInfo* m_fileInfo; + NZBInfo* m_nzbInfo; - EditItem(FileInfo* pFileInfo, NZBInfo* pNZBInfo, int iOffset); + EditItem(FileInfo* fileInfo, NZBInfo* nzbInfo, int offset); }; typedef std::vector ItemList; private: - DownloadQueue* m_pDownloadQueue; + DownloadQueue* m_downloadQueue; private: - FileInfo* FindFileInfo(int iID); - bool InternEditList(ItemList* pItemList, IDList* pIDList, DownloadQueue::EEditAction eAction, int iOffset, const char* szText); - void PrepareList(ItemList* pItemList, IDList* pIDList, DownloadQueue::EEditAction eAction, int iOffset); - bool BuildIDListFromNameList(IDList* pIDList, NameList* pNameList, DownloadQueue::EMatchMode eMatchMode, DownloadQueue::EEditAction eAction); - bool EditGroup(NZBInfo* pNZBInfo, DownloadQueue::EEditAction eAction, int iOffset, const char* szText); - void PauseParsInGroups(ItemList* pItemList, bool bExtraParsOnly); - void PausePars(FileList* pFileList, bool bExtraParsOnly); - void SetNZBPriority(NZBInfo* pNZBInfo, const char* szPriority); - void SetNZBCategory(NZBInfo* pNZBInfo, const char* szCategory, bool bApplyParams); - void SetNZBName(NZBInfo* pNZBInfo, const char* szName); - bool CanCleanupDisk(NZBInfo* pNZBInfo); - bool MergeGroups(ItemList* pItemList); - bool SortGroups(ItemList* pItemList, const char* szSort); - bool SplitGroup(ItemList* pItemList, const char* szName); - bool DeleteUrl(NZBInfo* pNZBInfo, DownloadQueue::EEditAction eAction); - void ReorderFiles(ItemList* pItemList); - void SetNZBParameter(NZBInfo* pNZBInfo, const char* szParamString); - void SetNZBDupeParam(NZBInfo* pNZBInfo, DownloadQueue::EEditAction eAction, const char* szText); - void PauseUnpauseEntry(FileInfo* pFileInfo, bool bPause); - void DeleteEntry(FileInfo* pFileInfo); - void MoveEntry(FileInfo* pFileInfo, int iOffset); - void MoveGroup(NZBInfo* pNZBInfo, int iOffset); + FileInfo* FindFileInfo(int id); + bool InternEditList(ItemList* itemList, IDList* idList, DownloadQueue::EEditAction action, int offset, const char* text); + void PrepareList(ItemList* itemList, IDList* idList, DownloadQueue::EEditAction action, int offset); + bool BuildIDListFromNameList(IDList* idList, NameList* nameList, DownloadQueue::EMatchMode matchMode, DownloadQueue::EEditAction action); + bool EditGroup(NZBInfo* nzbInfo, DownloadQueue::EEditAction action, int offset, const char* text); + void PauseParsInGroups(ItemList* itemList, bool extraParsOnly); + void PausePars(FileList* fileList, bool extraParsOnly); + void SetNZBPriority(NZBInfo* nzbInfo, const char* priority); + void SetNZBCategory(NZBInfo* nzbInfo, const char* category, bool applyParams); + void SetNZBName(NZBInfo* nzbInfo, const char* name); + bool CanCleanupDisk(NZBInfo* nzbInfo); + bool MergeGroups(ItemList* itemList); + bool SortGroups(ItemList* itemList, const char* sort); + bool SplitGroup(ItemList* itemList, const char* name); + bool DeleteUrl(NZBInfo* nzbInfo, DownloadQueue::EEditAction action); + void ReorderFiles(ItemList* itemList); + void SetNZBParameter(NZBInfo* nzbInfo, const char* paramString); + void SetNZBDupeParam(NZBInfo* nzbInfo, DownloadQueue::EEditAction action, const char* text); + void PauseUnpauseEntry(FileInfo* fileInfo, bool pause); + void DeleteEntry(FileInfo* fileInfo); + void MoveEntry(FileInfo* fileInfo, int offset); + void MoveGroup(NZBInfo* nzbInfo, int offset); public: QueueEditor(); ~QueueEditor(); - bool EditEntry(DownloadQueue* pDownloadQueue, int ID, DownloadQueue::EEditAction eAction, int iOffset, const char* szText); - bool EditList(DownloadQueue* pDownloadQueue, IDList* pIDList, NameList* pNameList, DownloadQueue::EMatchMode eMatchMode, DownloadQueue::EEditAction eAction, int iOffset, const char* szText); + bool EditEntry(DownloadQueue* downloadQueue, int ID, DownloadQueue::EEditAction action, int offset, const char* text); + bool EditList(DownloadQueue* downloadQueue, IDList* idList, NameList* nameList, DownloadQueue::EMatchMode matchMode, DownloadQueue::EEditAction action, int offset, const char* text); }; #endif diff --git a/daemon/queue/Scanner.cpp b/daemon/queue/Scanner.cpp index c046785a..c56506c5 100644 --- a/daemon/queue/Scanner.cpp +++ b/daemon/queue/Scanner.cpp @@ -50,64 +50,64 @@ #include "ScanScript.h" #include "Util.h" -Scanner::FileData::FileData(const char* szFilename) +Scanner::FileData::FileData(const char* filename) { - m_szFilename = strdup(szFilename); - m_iSize = 0; - m_tLastChange = 0; + m_filename = strdup(filename); + m_size = 0; + m_lastChange = 0; } Scanner::FileData::~FileData() { - free(m_szFilename); + free(m_filename); } -Scanner::QueueData::QueueData(const char* szFilename, const char* szNZBName, const char* szCategory, - int iPriority, const char* szDupeKey, int iDupeScore, EDupeMode eDupeMode, - NZBParameterList* pParameters, bool bAddTop, bool bAddPaused, NZBInfo* pUrlInfo, - EAddStatus* pAddStatus, int* pNZBID) +Scanner::QueueData::QueueData(const char* filename, const char* nzbName, const char* category, + int priority, const char* dupeKey, int dupeScore, EDupeMode dupeMode, + NZBParameterList* parameters, bool addTop, bool addPaused, NZBInfo* urlInfo, + EAddStatus* addStatus, int* nzbId) { - m_szFilename = strdup(szFilename); - m_szNZBName = strdup(szNZBName); - m_szCategory = strdup(szCategory ? szCategory : ""); - m_iPriority = iPriority; - m_szDupeKey = strdup(szDupeKey ? szDupeKey : ""); - m_iDupeScore = iDupeScore; - m_eDupeMode = eDupeMode; - m_bAddTop = bAddTop; - m_bAddPaused = bAddPaused; - m_pUrlInfo = pUrlInfo; - m_pAddStatus = pAddStatus; - m_pNZBID = pNZBID; + m_filename = strdup(filename); + m_nzbName = strdup(nzbName); + m_category = strdup(category ? category : ""); + m_priority = priority; + m_dupeKey = strdup(dupeKey ? dupeKey : ""); + m_dupeScore = dupeScore; + m_dupeMode = dupeMode; + m_addTop = addTop; + m_addPaused = addPaused; + m_urlInfo = urlInfo; + m_addStatus = addStatus; + m_nzbId = nzbId; - if (pParameters) + if (parameters) { - m_Parameters.CopyFrom(pParameters); + m_parameters.CopyFrom(parameters); } } Scanner::QueueData::~QueueData() { - free(m_szFilename); - free(m_szNZBName); - free(m_szCategory); - free(m_szDupeKey); + free(m_filename); + free(m_nzbName); + free(m_category); + free(m_dupeKey); } -void Scanner::QueueData::SetAddStatus(EAddStatus eAddStatus) +void Scanner::QueueData::SetAddStatus(EAddStatus addStatus) { - if (m_pAddStatus) + if (m_addStatus) { - *m_pAddStatus = eAddStatus; + *m_addStatus = addStatus; } } -void Scanner::QueueData::SetNZBID(int iNZBID) +void Scanner::QueueData::SetNZBID(int nzbId) { - if (m_pNZBID) + if (m_nzbId) { - *m_pNZBID = iNZBID; + *m_nzbId = nzbId; } } @@ -116,40 +116,40 @@ Scanner::Scanner() { debug("Creating Scanner"); - m_bRequestedNZBDirScan = false; - m_bScanning = false; - m_iNZBDirInterval = 0; - m_iPass = 0; - m_bScanScript = false; + m_requestedNzbDirScan = false; + m_scanning = false; + m_nzbDirInterval = 0; + m_pass = 0; + m_scanScript = false; } Scanner::~Scanner() { debug("Destroying Scanner"); - for (FileList::iterator it = m_FileList.begin(); it != m_FileList.end(); it++) + for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); it++) { delete *it; } - m_FileList.clear(); + m_fileList.clear(); ClearQueueList(); } void Scanner::InitOptions() { - m_iNZBDirInterval = g_pOptions->GetNzbDirInterval() * 1000; - const char* szScanScript = g_pOptions->GetScanScript(); - m_bScanScript = szScanScript && strlen(szScanScript) > 0; + m_nzbDirInterval = g_pOptions->GetNzbDirInterval() * 1000; + const char* scanScript = g_pOptions->GetScanScript(); + m_scanScript = scanScript && strlen(scanScript) > 0; } void Scanner::ClearQueueList() { - for (QueueList::iterator it = m_QueueList.begin(); it != m_QueueList.end(); it++) + for (QueueList::iterator it = m_queueList.begin(); it != m_queueList.end(); it++) { delete *it; } - m_QueueList.clear(); + m_queueList.clear(); } void Scanner::ServiceWork() @@ -159,24 +159,24 @@ void Scanner::ServiceWork() return; } - m_mutexScan.Lock(); + m_scanMutex.Lock(); - if (m_bRequestedNZBDirScan || + if (m_requestedNzbDirScan || (!g_pOptions->GetPauseScan() && g_pOptions->GetNzbDirInterval() > 0 && - m_iNZBDirInterval >= g_pOptions->GetNzbDirInterval() * 1000)) + m_nzbDirInterval >= g_pOptions->GetNzbDirInterval() * 1000)) { // check nzbdir every g_pOptions->GetNzbDirInterval() seconds or if requested - bool bCheckStat = !m_bRequestedNZBDirScan; - m_bRequestedNZBDirScan = false; - m_bScanning = true; - CheckIncomingNZBs(g_pOptions->GetNzbDir(), "", bCheckStat); - if (!bCheckStat && m_bScanScript) + bool checkStat = !m_requestedNzbDirScan; + m_requestedNzbDirScan = false; + m_scanning = true; + CheckIncomingNZBs(g_pOptions->GetNzbDir(), "", checkStat); + if (!checkStat && m_scanScript) { // if immediate scan requested, we need second scan to process files extracted by NzbProcess-script - CheckIncomingNZBs(g_pOptions->GetNzbDir(), "", bCheckStat); + CheckIncomingNZBs(g_pOptions->GetNzbDir(), "", checkStat); } - m_bScanning = false; - m_iNZBDirInterval = 0; + m_scanning = false; + m_nzbDirInterval = 0; // if NzbDirFileAge is less than NzbDirInterval (that can happen if NzbDirInterval // is set for rare scans like once per hour) we make 4 scans: @@ -185,58 +185,58 @@ void Scanner::ServiceWork() // - third scan is needed to check sizes of extracted files. if (g_pOptions->GetNzbDirInterval() > 0 && g_pOptions->GetNzbDirFileAge() < g_pOptions->GetNzbDirInterval()) { - int iMaxPass = m_bScanScript ? 3 : 1; - if (m_iPass < iMaxPass) + int maxPass = m_scanScript ? 3 : 1; + if (m_pass < maxPass) { // scheduling another scan of incoming directory in NzbDirFileAge seconds. - m_iNZBDirInterval = (g_pOptions->GetNzbDirInterval() - g_pOptions->GetNzbDirFileAge()) * 1000; - m_iPass++; + m_nzbDirInterval = (g_pOptions->GetNzbDirInterval() - g_pOptions->GetNzbDirFileAge()) * 1000; + m_pass++; } else { - m_iPass = 0; + m_pass = 0; } } DropOldFiles(); ClearQueueList(); } - m_iNZBDirInterval += 200; + m_nzbDirInterval += 200; - m_mutexScan.Unlock(); + m_scanMutex.Unlock(); } /** * Check if there are files in directory for incoming nzb-files * and add them to download queue */ -void Scanner::CheckIncomingNZBs(const char* szDirectory, const char* szCategory, bool bCheckStat) +void Scanner::CheckIncomingNZBs(const char* directory, const char* category, bool checkStat) { - DirBrowser dir(szDirectory); + DirBrowser dir(directory); while (const char* filename = dir.Next()) { char fullfilename[1023 + 1]; // one char reserved for the trailing slash (if needed) - snprintf(fullfilename, 1023, "%s%s", szDirectory, filename); + snprintf(fullfilename, 1023, "%s%s", directory, filename); fullfilename[1023 - 1] = '\0'; - bool bIsDirectory = Util::DirectoryExists(fullfilename); + bool isDirectory = Util::DirectoryExists(fullfilename); // check subfolders - if (bIsDirectory && strcmp(filename, ".") && strcmp(filename, "..")) + if (isDirectory && strcmp(filename, ".") && strcmp(filename, "..")) { fullfilename[strlen(fullfilename) + 1] = '\0'; fullfilename[strlen(fullfilename)] = PATH_SEPARATOR; - const char* szUseCategory = filename; - char szSubCategory[1024]; - if (strlen(szCategory) > 0) + const char* useCategory = filename; + char subCategory[1024]; + if (strlen(category) > 0) { - snprintf(szSubCategory, 1023, "%s%c%s", szCategory, PATH_SEPARATOR, filename); - szSubCategory[1024 - 1] = '\0'; - szUseCategory = szSubCategory; + snprintf(subCategory, 1023, "%s%c%s", category, PATH_SEPARATOR, filename); + subCategory[1024 - 1] = '\0'; + useCategory = subCategory; } - CheckIncomingNZBs(fullfilename, szUseCategory, bCheckStat); + CheckIncomingNZBs(fullfilename, useCategory, checkStat); } - else if (!bIsDirectory && CanProcessFile(fullfilename, bCheckStat)) + else if (!isDirectory && CanProcessFile(fullfilename, checkStat)) { - ProcessIncomingFile(szDirectory, filename, fullfilename, szCategory); + ProcessIncomingFile(directory, filename, fullfilename, category); } } } @@ -246,61 +246,61 @@ void Scanner::CheckIncomingNZBs(const char* szDirectory, const char* szCategory, * can be processed. That prevents the processing of files, which are currently being * copied into nzb-directory (eg. being downloaded in web-browser). */ -bool Scanner::CanProcessFile(const char* szFullFilename, bool bCheckStat) +bool Scanner::CanProcessFile(const char* fullFilename, bool checkStat) { - const char* szExtension = strrchr(szFullFilename, '.'); - if (!szExtension || - !strcasecmp(szExtension, ".queued") || - !strcasecmp(szExtension, ".error") || - !strcasecmp(szExtension, ".processed")) + const char* extension = strrchr(fullFilename, '.'); + if (!extension || + !strcasecmp(extension, ".queued") || + !strcasecmp(extension, ".error") || + !strcasecmp(extension, ".processed")) { return false; } - if (!bCheckStat) + if (!checkStat) { return true; } - long long lSize = Util::FileSize(szFullFilename); - time_t tCurrent = time(NULL); - bool bCanProcess = false; - bool bInList = false; + long long size = Util::FileSize(fullFilename); + time_t current = time(NULL); + bool canProcess = false; + bool inList = false; - for (FileList::iterator it = m_FileList.begin(); it != m_FileList.end(); it++) + for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); it++) { - FileData* pFileData = *it; - if (!strcmp(pFileData->GetFilename(), szFullFilename)) + FileData* fileData = *it; + if (!strcmp(fileData->GetFilename(), fullFilename)) { - bInList = true; - if (pFileData->GetSize() == lSize && - tCurrent - pFileData->GetLastChange() >= g_pOptions->GetNzbDirFileAge()) + inList = true; + if (fileData->GetSize() == size && + current - fileData->GetLastChange() >= g_pOptions->GetNzbDirFileAge()) { - bCanProcess = true; - delete pFileData; - m_FileList.erase(it); + canProcess = true; + delete fileData; + m_fileList.erase(it); } else { - pFileData->SetSize(lSize); - if (pFileData->GetSize() != lSize) + fileData->SetSize(size); + if (fileData->GetSize() != size) { - pFileData->SetLastChange(tCurrent); + fileData->SetLastChange(current); } } break; } } - if (!bInList) + if (!inList) { - FileData* pFileData = new FileData(szFullFilename); - pFileData->SetSize(lSize); - pFileData->SetLastChange(tCurrent); - m_FileList.push_back(pFileData); + FileData* fileData = new FileData(fullFilename); + fileData->SetSize(size); + fileData->SetLastChange(current); + m_fileList.push_back(fileData); } - return bCanProcess; + return canProcess; } /** @@ -312,22 +312,22 @@ bool Scanner::CanProcessFile(const char* szFullFilename, bool bCheckStat) */ void Scanner::DropOldFiles() { - time_t tCurrent = time(NULL); + time_t current = time(NULL); int i = 0; - for (FileList::iterator it = m_FileList.begin(); it != m_FileList.end(); ) + for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); ) { - FileData* pFileData = *it; - if ((tCurrent - pFileData->GetLastChange() >= + FileData* fileData = *it; + if ((current - fileData->GetLastChange() >= (g_pOptions->GetNzbDirInterval() + g_pOptions->GetNzbDirFileAge()) * 2) || // can occur if the system clock was adjusted - tCurrent < pFileData->GetLastChange()) + current < fileData->GetLastChange()) { - debug("Removing file %s from scan file list", pFileData->GetFilename()); + debug("Removing file %s from scan file list", fileData->GetFilename()); - delete pFileData; - m_FileList.erase(it); - it = m_FileList.begin() + i; + delete fileData; + m_fileList.erase(it); + it = m_fileList.begin() + i; } else { @@ -337,360 +337,360 @@ void Scanner::DropOldFiles() } } -void Scanner::ProcessIncomingFile(const char* szDirectory, const char* szBaseFilename, - const char* szFullFilename, const char* szCategory) +void Scanner::ProcessIncomingFile(const char* directory, const char* baseFilename, + const char* fullFilename, const char* category) { - const char* szExtension = strrchr(szBaseFilename, '.'); - if (!szExtension) + const char* extension = strrchr(baseFilename, '.'); + if (!extension) { return; } - char* szNZBName = strdup(""); - char* szNZBCategory = strdup(szCategory); - NZBParameterList* pParameters = new NZBParameterList(); - int iPriority = 0; - bool bAddTop = false; - bool bAddPaused = false; - char* szDupeKey = strdup(""); - int iDupeScore = 0; - EDupeMode eDupeMode = dmScore; - EAddStatus eAddStatus = asSkipped; - QueueData* pQueueData = NULL; - NZBInfo* pUrlInfo = NULL; - int iNZBID = 0; + char* nzbName = strdup(""); + char* nzbCategory = strdup(category); + NZBParameterList* parameters = new NZBParameterList(); + int priority = 0; + bool addTop = false; + bool addPaused = false; + char* dupeKey = strdup(""); + int dupeScore = 0; + EDupeMode dupeMode = dmScore; + EAddStatus addStatus = asSkipped; + QueueData* queueData = NULL; + NZBInfo* urlInfo = NULL; + int nzbId = 0; - for (QueueList::iterator it = m_QueueList.begin(); it != m_QueueList.end(); it++) + for (QueueList::iterator it = m_queueList.begin(); it != m_queueList.end(); it++) { - QueueData* pQueueData1 = *it; - if (Util::SameFilename(pQueueData1->GetFilename(), szFullFilename)) + QueueData* queueData1 = *it; + if (Util::SameFilename(queueData1->GetFilename(), fullFilename)) { - pQueueData = pQueueData1; - free(szNZBName); - szNZBName = strdup(pQueueData->GetNZBName()); - free(szNZBCategory); - szNZBCategory = strdup(pQueueData->GetCategory()); - iPriority = pQueueData->GetPriority(); - free(szDupeKey); - szDupeKey = strdup(pQueueData->GetDupeKey()); - iDupeScore = pQueueData->GetDupeScore(); - eDupeMode = pQueueData->GetDupeMode(); - bAddTop = pQueueData->GetAddTop(); - bAddPaused = pQueueData->GetAddPaused(); - pParameters->CopyFrom(pQueueData->GetParameters()); - pUrlInfo = pQueueData->GetUrlInfo(); + queueData = queueData1; + free(nzbName); + nzbName = strdup(queueData->GetNZBName()); + free(nzbCategory); + nzbCategory = strdup(queueData->GetCategory()); + priority = queueData->GetPriority(); + free(dupeKey); + dupeKey = strdup(queueData->GetDupeKey()); + dupeScore = queueData->GetDupeScore(); + dupeMode = queueData->GetDupeMode(); + addTop = queueData->GetAddTop(); + addPaused = queueData->GetAddPaused(); + parameters->CopyFrom(queueData->GetParameters()); + urlInfo = queueData->GetUrlInfo(); } } - InitPPParameters(szNZBCategory, pParameters, false); + InitPPParameters(nzbCategory, parameters, false); - bool bExists = true; + bool exists = true; - if (m_bScanScript && strcasecmp(szExtension, ".nzb_processed")) + if (m_scanScript && strcasecmp(extension, ".nzb_processed")) { - ScanScriptController::ExecuteScripts(szFullFilename, - pUrlInfo ? pUrlInfo->GetURL() : "", szDirectory, - &szNZBName, &szNZBCategory, &iPriority, pParameters, &bAddTop, - &bAddPaused, &szDupeKey, &iDupeScore, &eDupeMode); - bExists = Util::FileExists(szFullFilename); - if (bExists && strcasecmp(szExtension, ".nzb")) + ScanScriptController::ExecuteScripts(fullFilename, + urlInfo ? urlInfo->GetURL() : "", directory, + &nzbName, &nzbCategory, &priority, parameters, &addTop, + &addPaused, &dupeKey, &dupeScore, &dupeMode); + exists = Util::FileExists(fullFilename); + if (exists && strcasecmp(extension, ".nzb")) { char bakname2[1024]; - bool bRenameOK = Util::RenameBak(szFullFilename, "processed", false, bakname2, 1024); - if (!bRenameOK) + bool renameOK = Util::RenameBak(fullFilename, "processed", false, bakname2, 1024); + if (!renameOK) { - char szSysErrStr[256]; - error("Could not rename file %s to %s: %s", szFullFilename, bakname2, Util::GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); + char sysErrStr[256]; + error("Could not rename file %s to %s: %s", fullFilename, bakname2, Util::GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); } } } - if (!strcasecmp(szExtension, ".nzb_processed")) + if (!strcasecmp(extension, ".nzb_processed")) { - char szRenamedName[1024]; - bool bRenameOK = Util::RenameBak(szFullFilename, "nzb", true, szRenamedName, 1024); - if (bRenameOK) + char renamedName[1024]; + bool renameOK = Util::RenameBak(fullFilename, "nzb", true, renamedName, 1024); + if (renameOK) { - bool bAdded = AddFileToQueue(szRenamedName, szNZBName, szNZBCategory, iPriority, - szDupeKey, iDupeScore, eDupeMode, pParameters, bAddTop, bAddPaused, pUrlInfo, &iNZBID); - eAddStatus = bAdded ? asSuccess : asFailed; + bool added = AddFileToQueue(renamedName, nzbName, nzbCategory, priority, + dupeKey, dupeScore, dupeMode, parameters, addTop, addPaused, urlInfo, &nzbId); + addStatus = added ? asSuccess : asFailed; } else { - char szSysErrStr[256]; - error("Could not rename file %s to %s: %s", szFullFilename, szRenamedName, Util::GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); - eAddStatus = asFailed; + char sysErrStr[256]; + error("Could not rename file %s to %s: %s", fullFilename, renamedName, Util::GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); + addStatus = asFailed; } } - else if (bExists && !strcasecmp(szExtension, ".nzb")) + else if (exists && !strcasecmp(extension, ".nzb")) { - bool bAdded = AddFileToQueue(szFullFilename, szNZBName, szNZBCategory, iPriority, - szDupeKey, iDupeScore, eDupeMode, pParameters, bAddTop, bAddPaused, pUrlInfo, &iNZBID); - eAddStatus = bAdded ? asSuccess : asFailed; + bool added = AddFileToQueue(fullFilename, nzbName, nzbCategory, priority, + dupeKey, dupeScore, dupeMode, parameters, addTop, addPaused, urlInfo, &nzbId); + addStatus = added ? asSuccess : asFailed; } - delete pParameters; + delete parameters; - free(szNZBName); - free(szNZBCategory); - free(szDupeKey); + free(nzbName); + free(nzbCategory); + free(dupeKey); - if (pQueueData) + if (queueData) { - pQueueData->SetAddStatus(eAddStatus); - pQueueData->SetNZBID(iNZBID); + queueData->SetAddStatus(addStatus); + queueData->SetNZBID(nzbId); } } -void Scanner::InitPPParameters(const char* szCategory, NZBParameterList* pParameters, bool bReset) +void Scanner::InitPPParameters(const char* category, NZBParameterList* parameters, bool reset) { - bool bUnpack = g_pOptions->GetUnpack(); - const char* szPostScript = g_pOptions->GetPostScript(); + bool unpack = g_pOptions->GetUnpack(); + const char* postScript = g_pOptions->GetPostScript(); - if (!Util::EmptyStr(szCategory)) + if (!Util::EmptyStr(category)) { - Options::Category* pCategory = g_pOptions->FindCategory(szCategory, false); - if (pCategory) + Options::Category* categoryObj = g_pOptions->FindCategory(category, false); + if (categoryObj) { - bUnpack = pCategory->GetUnpack(); - if (!Util::EmptyStr(pCategory->GetPostScript())) + unpack = categoryObj->GetUnpack(); + if (!Util::EmptyStr(categoryObj->GetPostScript())) { - szPostScript = pCategory->GetPostScript(); + postScript = categoryObj->GetPostScript(); } } } - if (bReset) + if (reset) { for (ScriptConfig::Scripts::iterator it = g_pScriptConfig->GetScripts()->begin(); it != g_pScriptConfig->GetScripts()->end(); it++) { - ScriptConfig::Script* pScript = *it; - char szParam[1024]; - snprintf(szParam, 1024, "%s:", pScript->GetName()); - szParam[1024-1] = '\0'; - pParameters->SetParameter(szParam, NULL); + ScriptConfig::Script* script = *it; + char param[1024]; + snprintf(param, 1024, "%s:", script->GetName()); + param[1024-1] = '\0'; + parameters->SetParameter(param, NULL); } } - pParameters->SetParameter("*Unpack:", bUnpack ? "yes" : "no"); + parameters->SetParameter("*Unpack:", unpack ? "yes" : "no"); - if (!Util::EmptyStr(szPostScript)) + if (!Util::EmptyStr(postScript)) { // split szPostScript into tokens and create pp-parameter for each token - Tokenizer tok(szPostScript, ",;"); - while (const char* szScriptName = tok.Next()) + Tokenizer tok(postScript, ",;"); + while (const char* scriptName = tok.Next()) { - char szParam[1024]; - snprintf(szParam, 1024, "%s:", szScriptName); - szParam[1024-1] = '\0'; - pParameters->SetParameter(szParam, "yes"); + char param[1024]; + snprintf(param, 1024, "%s:", scriptName); + param[1024-1] = '\0'; + parameters->SetParameter(param, "yes"); } } } -bool Scanner::AddFileToQueue(const char* szFilename, const char* szNZBName, const char* szCategory, - int iPriority, const char* szDupeKey, int iDupeScore, EDupeMode eDupeMode, - NZBParameterList* pParameters, bool bAddTop, bool bAddPaused, NZBInfo* pUrlInfo, int* pNZBID) +bool Scanner::AddFileToQueue(const char* filename, const char* nzbName, const char* category, + int priority, const char* dupeKey, int dupeScore, EDupeMode dupeMode, + NZBParameterList* parameters, bool addTop, bool addPaused, NZBInfo* urlInfo, int* nzbId) { - const char* szBasename = Util::BaseFileName(szFilename); + const char* basename = Util::BaseFileName(filename); - info("Adding collection %s to queue", szBasename); + info("Adding collection %s to queue", basename); - NZBFile* pNZBFile = new NZBFile(szFilename, szCategory); - bool bOK = pNZBFile->Parse(); - if (!bOK) + NZBFile* nzbFile = new NZBFile(filename, category); + bool ok = nzbFile->Parse(); + if (!ok) { - error("Could not add collection %s to queue", szBasename); + error("Could not add collection %s to queue", basename); } char bakname2[1024]; - if (!Util::RenameBak(szFilename, pNZBFile ? "queued" : "error", false, bakname2, 1024)) + if (!Util::RenameBak(filename, nzbFile ? "queued" : "error", false, bakname2, 1024)) { - bOK = false; - char szSysErrStr[256]; - error("Could not rename file %s to %s: %s", szFilename, bakname2, Util::GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); + ok = false; + char sysErrStr[256]; + error("Could not rename file %s to %s: %s", filename, bakname2, Util::GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); } - NZBInfo* pNZBInfo = pNZBFile->GetNZBInfo(); - pNZBInfo->SetQueuedFilename(bakname2); + NZBInfo* nzbInfo = nzbFile->GetNZBInfo(); + nzbInfo->SetQueuedFilename(bakname2); - if (szNZBName && strlen(szNZBName) > 0) + if (nzbName && strlen(nzbName) > 0) { - pNZBInfo->SetName(NULL); + nzbInfo->SetName(NULL); #ifdef WIN32 - char* szAnsiFilename = strdup(szNZBName); - WebUtil::Utf8ToAnsi(szAnsiFilename, strlen(szAnsiFilename) + 1); - pNZBInfo->SetFilename(szAnsiFilename); - free(szAnsiFilename); + char* ansiFilename = strdup(nzbName); + WebUtil::Utf8ToAnsi(ansiFilename, strlen(ansiFilename) + 1); + nzbInfo->SetFilename(ansiFilename); + free(ansiFilename); #else - pNZBInfo->SetFilename(szNZBName); + nzbInfo->SetFilename(nzbName); #endif - pNZBInfo->BuildDestDirName(); + nzbInfo->BuildDestDirName(); } - pNZBInfo->SetDupeKey(szDupeKey); - pNZBInfo->SetDupeScore(iDupeScore); - pNZBInfo->SetDupeMode(eDupeMode); - pNZBInfo->SetPriority(iPriority); - if (pUrlInfo) + nzbInfo->SetDupeKey(dupeKey); + nzbInfo->SetDupeScore(dupeScore); + nzbInfo->SetDupeMode(dupeMode); + nzbInfo->SetPriority(priority); + if (urlInfo) { - pNZBInfo->SetURL(pUrlInfo->GetURL()); - pNZBInfo->SetUrlStatus(pUrlInfo->GetUrlStatus()); - pNZBInfo->SetFeedID(pUrlInfo->GetFeedID()); + nzbInfo->SetURL(urlInfo->GetURL()); + nzbInfo->SetUrlStatus(urlInfo->GetUrlStatus()); + nzbInfo->SetFeedID(urlInfo->GetFeedID()); } - if (pNZBFile->GetPassword()) + if (nzbFile->GetPassword()) { - pNZBInfo->GetParameters()->SetParameter("*Unpack:Password", pNZBFile->GetPassword()); + nzbInfo->GetParameters()->SetParameter("*Unpack:Password", nzbFile->GetPassword()); } - pNZBInfo->GetParameters()->CopyFrom(pParameters); + nzbInfo->GetParameters()->CopyFrom(parameters); - for (::FileList::iterator it = pNZBInfo->GetFileList()->begin(); it != pNZBInfo->GetFileList()->end(); it++) + for (::FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) { - FileInfo* pFileInfo = *it; - pFileInfo->SetPaused(bAddPaused); + FileInfo* fileInfo = *it; + fileInfo->SetPaused(addPaused); } - if (bOK) + if (ok) { - g_pQueueCoordinator->AddNZBFileToQueue(pNZBFile, pUrlInfo, bAddTop); + g_pQueueCoordinator->AddNZBFileToQueue(nzbFile, urlInfo, addTop); } - else if (!pUrlInfo) + else if (!urlInfo) { - pNZBFile->GetNZBInfo()->SetDeleteStatus(NZBInfo::dsScan); - g_pQueueCoordinator->AddNZBFileToQueue(pNZBFile, pUrlInfo, bAddTop); + nzbFile->GetNZBInfo()->SetDeleteStatus(NZBInfo::dsScan); + g_pQueueCoordinator->AddNZBFileToQueue(nzbFile, urlInfo, addTop); } - if (pNZBID) + if (nzbId) { - *pNZBID = pNZBInfo->GetID(); + *nzbId = nzbInfo->GetID(); } - delete pNZBFile; + delete nzbFile; - return bOK; + return ok; } -void Scanner::ScanNZBDir(bool bSyncMode) +void Scanner::ScanNZBDir(bool syncMode) { - m_mutexScan.Lock(); - m_bScanning = true; - m_bRequestedNZBDirScan = true; - m_mutexScan.Unlock(); + m_scanMutex.Lock(); + m_scanning = true; + m_requestedNzbDirScan = true; + m_scanMutex.Unlock(); - while (bSyncMode && (m_bScanning || m_bRequestedNZBDirScan)) + while (syncMode && (m_scanning || m_requestedNzbDirScan)) { usleep(100 * 1000); } } -Scanner::EAddStatus Scanner::AddExternalFile(const char* szNZBName, const char* szCategory, - int iPriority, const char* szDupeKey, int iDupeScore, EDupeMode eDupeMode, - NZBParameterList* pParameters, bool bAddTop, bool bAddPaused, NZBInfo* pUrlInfo, - const char* szFileName, const char* szBuffer, int iBufSize, int* pNZBID) +Scanner::EAddStatus Scanner::AddExternalFile(const char* nzbName, const char* category, + int priority, const char* dupeKey, int dupeScore, EDupeMode dupeMode, + NZBParameterList* parameters, bool addTop, bool addPaused, NZBInfo* urlInfo, + const char* fileName, const char* buffer, int bufSize, int* nzbId) { - bool bNZB = false; - char szTempFileName[1024]; + bool nzb = false; + char tempFileName[1024]; - if (szFileName) + if (fileName) { - strncpy(szTempFileName, szFileName, 1024); - szTempFileName[1024-1] = '\0'; + strncpy(tempFileName, fileName, 1024); + tempFileName[1024-1] = '\0'; } else { - int iNum = 1; - while (iNum == 1 || Util::FileExists(szTempFileName)) + int num = 1; + while (num == 1 || Util::FileExists(tempFileName)) { - snprintf(szTempFileName, 1024, "%snzb-%i.tmp", g_pOptions->GetTempDir(), iNum); - szTempFileName[1024-1] = '\0'; - iNum++; + snprintf(tempFileName, 1024, "%snzb-%i.tmp", g_pOptions->GetTempDir(), num); + tempFileName[1024-1] = '\0'; + num++; } - if (!Util::SaveBufferIntoFile(szTempFileName, szBuffer, iBufSize)) + if (!Util::SaveBufferIntoFile(tempFileName, buffer, bufSize)) { - error("Could not create file %s", szTempFileName); + error("Could not create file %s", tempFileName); return asFailed; } char buf[1024]; - strncpy(buf, szBuffer, 1024); + strncpy(buf, buffer, 1024); buf[1024-1] = '\0'; - bNZB = !strncmp(buf, "GetNzbDir(), szValidNZBName); + char scanFileName[1024]; + snprintf(scanFileName, 1024, "%s%s", g_pOptions->GetNzbDir(), validNzbName); - char *szExt = strrchr(szValidNZBName, '.'); - if (szExt) + char *ext = strrchr(validNzbName, '.'); + if (ext) { - *szExt = '\0'; - szExt++; + *ext = '\0'; + ext++; } - int iNum = 2; - while (Util::FileExists(szScanFileName)) + int num = 2; + while (Util::FileExists(scanFileName)) { - if (szExt) + if (ext) { - snprintf(szScanFileName, 1024, "%s%s_%i.%s", g_pOptions->GetNzbDir(), szValidNZBName, iNum, szExt); + snprintf(scanFileName, 1024, "%s%s_%i.%s", g_pOptions->GetNzbDir(), validNzbName, num, ext); } else { - snprintf(szScanFileName, 1024, "%s%s_%i", g_pOptions->GetNzbDir(), szValidNZBName, iNum); + snprintf(scanFileName, 1024, "%s%s_%i", g_pOptions->GetNzbDir(), validNzbName, num); } - szScanFileName[1024-1] = '\0'; - iNum++; + scanFileName[1024-1] = '\0'; + num++; } - m_mutexScan.Lock(); + m_scanMutex.Lock(); - if (!Util::MoveFile(szTempFileName, szScanFileName)) + if (!Util::MoveFile(tempFileName, scanFileName)) { - char szSysErrStr[256]; - error("Could not move file %s to %s: %s", szTempFileName, szScanFileName, Util::GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); - remove(szTempFileName); - m_mutexScan.Unlock(); // UNLOCK + char sysErrStr[256]; + error("Could not move file %s to %s: %s", tempFileName, scanFileName, Util::GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); + remove(tempFileName); + m_scanMutex.Unlock(); // UNLOCK return asFailed; } - char* szUseCategory = strdup(szCategory ? szCategory : ""); - Options::Category *pCategory = g_pOptions->FindCategory(szUseCategory, true); - if (pCategory && strcmp(szUseCategory, pCategory->GetName())) + char* useCategory = strdup(category ? category : ""); + Options::Category* categoryObj = g_pOptions->FindCategory(useCategory, true); + if (categoryObj && strcmp(useCategory, categoryObj->GetName())) { - free(szUseCategory); - szUseCategory = strdup(pCategory->GetName()); - detail("Category %s matched to %s for %s", szCategory, szUseCategory, szNZBName); + free(useCategory); + useCategory = strdup(categoryObj->GetName()); + detail("Category %s matched to %s for %s", category, useCategory, nzbName); } - EAddStatus eAddStatus = asSkipped; - QueueData* pQueueData = new QueueData(szScanFileName, szNZBName, szUseCategory, iPriority, - szDupeKey, iDupeScore, eDupeMode, pParameters, bAddTop, bAddPaused, pUrlInfo, - &eAddStatus, pNZBID); - free(szUseCategory); - m_QueueList.push_back(pQueueData); + EAddStatus addStatus = asSkipped; + QueueData* queueData = new QueueData(scanFileName, nzbName, useCategory, priority, + dupeKey, dupeScore, dupeMode, parameters, addTop, addPaused, urlInfo, + &addStatus, nzbId); + free(useCategory); + m_queueList.push_back(queueData); - m_mutexScan.Unlock(); + m_scanMutex.Unlock(); ScanNZBDir(true); - return eAddStatus; + return addStatus; } diff --git a/daemon/queue/Scanner.h b/daemon/queue/Scanner.h index 8461fbc0..f0d57130 100644 --- a/daemon/queue/Scanner.h +++ b/daemon/queue/Scanner.h @@ -46,18 +46,18 @@ private: class FileData { private: - char* m_szFilename; - long long m_iSize; - time_t m_tLastChange; + char* m_filename; + long long m_size; + time_t m_lastChange; public: - FileData(const char* szFilename); + FileData(const char* filename); ~FileData(); - const char* GetFilename() { return m_szFilename; } - long long GetSize() { return m_iSize; } - void SetSize(long long lSize) { m_iSize = lSize; } - time_t GetLastChange() { return m_tLastChange; } - void SetLastChange(time_t tLastChange) { m_tLastChange = tLastChange; } + const char* GetFilename() { return m_filename; } + long long GetSize() { return m_size; } + void SetSize(long long size) { m_size = size; } + time_t GetLastChange() { return m_lastChange; } + void SetLastChange(time_t lastChange) { m_lastChange = lastChange; } }; typedef std::deque FileList; @@ -65,59 +65,59 @@ private: class QueueData { private: - char* m_szFilename; - char* m_szNZBName; - char* m_szCategory; - int m_iPriority; - char* m_szDupeKey; - int m_iDupeScore; - EDupeMode m_eDupeMode; - NZBParameterList m_Parameters; - bool m_bAddTop; - bool m_bAddPaused; - NZBInfo* m_pUrlInfo; - EAddStatus* m_pAddStatus; - int* m_pNZBID; + char* m_filename; + char* m_nzbName; + char* m_category; + int m_priority; + char* m_dupeKey; + int m_dupeScore; + EDupeMode m_dupeMode; + NZBParameterList m_parameters; + bool m_addTop; + bool m_addPaused; + NZBInfo* m_urlInfo; + EAddStatus* m_addStatus; + int* m_nzbId; public: - QueueData(const char* szFilename, const char* szNZBName, const char* szCategory, - int iPriority, const char* szDupeKey, int iDupeScore, EDupeMode eDupeMode, - NZBParameterList* pParameters, bool bAddTop, bool bAddPaused, NZBInfo* pUrlInfo, - EAddStatus* pAddStatus, int* pNZBID); + QueueData(const char* filename, const char* nzbName, const char* category, + int priority, const char* dupeKey, int dupeScore, EDupeMode dupeMode, + NZBParameterList* parameters, bool addTop, bool addPaused, NZBInfo* urlInfo, + EAddStatus* addStatus, int* nzbId); ~QueueData(); - const char* GetFilename() { return m_szFilename; } - const char* GetNZBName() { return m_szNZBName; } - const char* GetCategory() { return m_szCategory; } - int GetPriority() { return m_iPriority; } - const char* GetDupeKey() { return m_szDupeKey; } - int GetDupeScore() { return m_iDupeScore; } - EDupeMode GetDupeMode() { return m_eDupeMode; } - NZBParameterList* GetParameters() { return &m_Parameters; } - bool GetAddTop() { return m_bAddTop; } - bool GetAddPaused() { return m_bAddPaused; } - NZBInfo* GetUrlInfo() { return m_pUrlInfo; } - void SetAddStatus(EAddStatus eAddStatus); - void SetNZBID(int iNZBID); + const char* GetFilename() { return m_filename; } + const char* GetNZBName() { return m_nzbName; } + const char* GetCategory() { return m_category; } + int GetPriority() { return m_priority; } + const char* GetDupeKey() { return m_dupeKey; } + int GetDupeScore() { return m_dupeScore; } + EDupeMode GetDupeMode() { return m_dupeMode; } + NZBParameterList* GetParameters() { return &m_parameters; } + bool GetAddTop() { return m_addTop; } + bool GetAddPaused() { return m_addPaused; } + NZBInfo* GetUrlInfo() { return m_urlInfo; } + void SetAddStatus(EAddStatus addStatus); + void SetNZBID(int nzbId); }; typedef std::deque QueueList; - bool m_bRequestedNZBDirScan; - int m_iNZBDirInterval; - bool m_bScanScript; - int m_iPass; - FileList m_FileList; - QueueList m_QueueList; - bool m_bScanning; - Mutex m_mutexScan; + bool m_requestedNzbDirScan; + int m_nzbDirInterval; + bool m_scanScript; + int m_pass; + FileList m_fileList; + QueueList m_queueList; + bool m_scanning; + Mutex m_scanMutex; - void CheckIncomingNZBs(const char* szDirectory, const char* szCategory, bool bCheckStat); - bool AddFileToQueue(const char* szFilename, const char* szNZBName, const char* szCategory, - int iPriority, const char* szDupeKey, int iDupeScore, EDupeMode eDupeMode, - NZBParameterList* pParameters, bool bAddTop, bool bAddPaused, NZBInfo* pUrlInfo, int* pNZBID); - void ProcessIncomingFile(const char* szDirectory, const char* szBaseFilename, - const char* szFullFilename, const char* szCategory); - bool CanProcessFile(const char* szFullFilename, bool bCheckStat); + void CheckIncomingNZBs(const char* directory, const char* category, bool checkStat); + bool AddFileToQueue(const char* filename, const char* nzbName, const char* category, + int priority, const char* dupeKey, int dupeScore, EDupeMode dupeMode, + NZBParameterList* parameters, bool addTop, bool addPaused, NZBInfo* urlInfo, int* nzbId); + void ProcessIncomingFile(const char* directory, const char* baseFilename, + const char* fullFilename, const char* category); + bool CanProcessFile(const char* fullFilename, bool checkStat); void DropOldFiles(); void ClearQueueList(); @@ -129,12 +129,12 @@ public: Scanner(); ~Scanner(); void InitOptions(); - void ScanNZBDir(bool bSyncMode); - EAddStatus AddExternalFile(const char* szNZBName, const char* szCategory, int iPriority, - const char* szDupeKey, int iDupeScore, EDupeMode eDupeMode, - NZBParameterList* pParameters, bool bAddTop, bool bAddPaused, NZBInfo* pUrlInfo, - const char* szFileName, const char* szBuffer, int iBufSize, int* pNZBID); - void InitPPParameters(const char* szCategory, NZBParameterList* pParameters, bool bReset); + void ScanNZBDir(bool syncMode); + EAddStatus AddExternalFile(const char* nzbName, const char* category, int priority, + const char* dupeKey, int dupeScore, EDupeMode dupeMode, + NZBParameterList* parameters, bool addTop, bool addPaused, NZBInfo* urlInfo, + const char* fileName, const char* buffer, int bufSize, int* nzbId); + void InitPPParameters(const char* category, NZBParameterList* parameters, bool reset); }; extern Scanner* g_pScanner; diff --git a/daemon/queue/UrlCoordinator.cpp b/daemon/queue/UrlCoordinator.cpp index 7f70a657..8eef9d40 100644 --- a/daemon/queue/UrlCoordinator.cpp +++ b/daemon/queue/UrlCoordinator.cpp @@ -52,50 +52,50 @@ UrlDownloader::UrlDownloader() : WebDownloader() { - m_szCategory = NULL; + m_category = NULL; } UrlDownloader::~UrlDownloader() { - free(m_szCategory); + free(m_category); } -void UrlDownloader::ProcessHeader(const char* szLine) +void UrlDownloader::ProcessHeader(const char* line) { - WebDownloader::ProcessHeader(szLine); + WebDownloader::ProcessHeader(line); - if (!strncmp(szLine, "X-DNZB-Category:", 16)) + if (!strncmp(line, "X-DNZB-Category:", 16)) { - free(m_szCategory); - char* szCategory = strdup(szLine + 16); - m_szCategory = strdup(Util::Trim(szCategory)); - free(szCategory); + free(m_category); + char* category = strdup(line + 16); + m_category = strdup(Util::Trim(category)); + free(category); - debug("Category: %s", m_szCategory); + debug("Category: %s", m_category); } - else if (!strncmp(szLine, "X-DNZB-", 7)) + else if (!strncmp(line, "X-DNZB-", 7)) { - char* szModLine = strdup(szLine); - char* szValue = strchr(szModLine, ':'); - if (szValue) + char* modLine = strdup(line); + char* value = strchr(modLine, ':'); + if (value) { - *szValue = '\0'; - szValue++; - while (*szValue == ' ') szValue++; - Util::Trim(szValue); + *value = '\0'; + value++; + while (*value == ' ') value++; + Util::Trim(value); - debug("X-DNZB: %s", szModLine); - debug("Value: %s", szValue); + debug("X-DNZB: %s", modLine); + debug("Value: %s", value); - char szParamName[100]; - snprintf(szParamName, 100, "*DNZB:%s", szModLine + 7); - szParamName[100-1] = '\0'; + char paramName[100]; + snprintf(paramName, 100, "*DNZB:%s", modLine + 7); + paramName[100-1] = '\0'; - char* szVal = WebUtil::Latin1ToUtf8(szValue); - m_pNZBInfo->GetParameters()->SetParameter(szParamName, szVal); - free(szVal); + char* val = WebUtil::Latin1ToUtf8(value); + m_nzbInfo->GetParameters()->SetParameter(paramName, val); + free(val); } - free(szModLine); + free(modLine); } } @@ -103,7 +103,7 @@ UrlCoordinator::UrlCoordinator() { debug("Creating UrlCoordinator"); - m_bHasMoreJobs = true; + m_hasMoreJobs = true; g_pLog->RegisterDebuggable(this); } @@ -116,11 +116,11 @@ UrlCoordinator::~UrlCoordinator() g_pLog->UnregisterDebuggable(this); debug("Deleting UrlDownloaders"); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { delete *it; } - m_ActiveDownloads.clear(); + m_activeDownloads.clear(); debug("UrlCoordinator destroyed"); } @@ -134,39 +134,39 @@ void UrlCoordinator::Run() usleep(20 * 1000); } - int iResetCounter = 0; + int resetCounter = 0; while (!IsStopped()) { - bool bDownloadStarted = false; + bool downloadStarted = false; if (!g_pOptions->GetPauseDownload() || g_pOptions->GetUrlForce()) { // start download for next URL - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - if ((int)m_ActiveDownloads.size() < g_pOptions->GetUrlConnections()) + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + if ((int)m_activeDownloads.size() < g_pOptions->GetUrlConnections()) { - NZBInfo* pNZBInfo = GetNextUrl(pDownloadQueue); - bool bHasMoreUrls = pNZBInfo != NULL; - bool bUrlDownloadsRunning = !m_ActiveDownloads.empty(); - m_bHasMoreJobs = bHasMoreUrls || bUrlDownloadsRunning; - if (bHasMoreUrls && !IsStopped()) + NZBInfo* nzbInfo = GetNextUrl(downloadQueue); + bool hasMoreUrls = nzbInfo != NULL; + bool urlDownloadsRunning = !m_activeDownloads.empty(); + m_hasMoreJobs = hasMoreUrls || urlDownloadsRunning; + if (hasMoreUrls && !IsStopped()) { - StartUrlDownload(pNZBInfo); - bDownloadStarted = true; + StartUrlDownload(nzbInfo); + downloadStarted = true; } } DownloadQueue::Unlock(); } - int iSleepInterval = bDownloadStarted ? 0 : 100; - usleep(iSleepInterval * 1000); + int sleepInterval = downloadStarted ? 0 : 100; + usleep(sleepInterval * 1000); - iResetCounter += iSleepInterval; - if (iResetCounter >= 1000) + resetCounter += sleepInterval; + if (resetCounter >= 1000) { // this code should not be called too often, once per second is OK ResetHangingDownloads(); - iResetCounter = 0; + resetCounter = 0; } } @@ -176,7 +176,7 @@ void UrlCoordinator::Run() while (!completed) { DownloadQueue::Lock(); - completed = m_ActiveDownloads.size() == 0; + completed = m_activeDownloads.size() == 0; DownloadQueue::Unlock(); usleep(100 * 1000); ResetHangingDownloads(); @@ -192,7 +192,7 @@ void UrlCoordinator::Stop() debug("Stopping UrlDownloads"); DownloadQueue::Lock(); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { (*it)->Stop(); } @@ -211,27 +211,27 @@ void UrlCoordinator::ResetHangingDownloads() DownloadQueue::Lock(); time_t tm = time(NULL); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end();) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end();) { - UrlDownloader* pUrlDownloader = *it; - if (tm - pUrlDownloader->GetLastUpdateTime() > TimeOut && - pUrlDownloader->GetStatus() == UrlDownloader::adRunning) + UrlDownloader* urlDownloader = *it; + if (tm - urlDownloader->GetLastUpdateTime() > TimeOut && + urlDownloader->GetStatus() == UrlDownloader::adRunning) { - NZBInfo* pNZBInfo = pUrlDownloader->GetNZBInfo(); - debug("Terminating hanging download %s", pUrlDownloader->GetInfoName()); - if (pUrlDownloader->Terminate()) + NZBInfo* nzbInfo = urlDownloader->GetNZBInfo(); + debug("Terminating hanging download %s", urlDownloader->GetInfoName()); + if (urlDownloader->Terminate()) { - error("Terminated hanging download %s", pUrlDownloader->GetInfoName()); - pNZBInfo->SetUrlStatus(NZBInfo::lsNone); + error("Terminated hanging download %s", urlDownloader->GetInfoName()); + nzbInfo->SetUrlStatus(NZBInfo::lsNone); } else { - error("Could not terminate hanging download %s", pUrlDownloader->GetInfoName()); + error("Could not terminate hanging download %s", urlDownloader->GetInfoName()); } - m_ActiveDownloads.erase(it); + m_activeDownloads.erase(it); // it's not safe to destroy pUrlDownloader, because the state of object is unknown - delete pUrlDownloader; - it = m_ActiveDownloads.begin(); + delete urlDownloader; + it = m_activeDownloads.begin(); continue; } it++; @@ -245,112 +245,112 @@ void UrlCoordinator::LogDebugInfo() info(" ---------- UrlCoordinator"); DownloadQueue::Lock(); - info(" Active Downloads: %i", m_ActiveDownloads.size()); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + info(" Active Downloads: %i", m_activeDownloads.size()); + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { - UrlDownloader* pUrlDownloader = *it; - pUrlDownloader->LogDebugInfo(); + UrlDownloader* urlDownloader = *it; + urlDownloader->LogDebugInfo(); } DownloadQueue::Unlock(); } -void UrlCoordinator::AddUrlToQueue(NZBInfo* pNZBInfo, bool bAddTop) +void UrlCoordinator::AddUrlToQueue(NZBInfo* nzbInfo, bool addTop) { debug("Adding NZB-URL to queue"); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - if (bAddTop) + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + if (addTop) { - pDownloadQueue->GetQueue()->push_front(pNZBInfo); + downloadQueue->GetQueue()->push_front(nzbInfo); } else { - pDownloadQueue->GetQueue()->push_back(pNZBInfo); + downloadQueue->GetQueue()->push_back(nzbInfo); } - pDownloadQueue->Save(); + downloadQueue->Save(); DownloadQueue::Unlock(); } /* * Returns next URL for download. */ -NZBInfo* UrlCoordinator::GetNextUrl(DownloadQueue* pDownloadQueue) +NZBInfo* UrlCoordinator::GetNextUrl(DownloadQueue* downloadQueue) { - bool bPauseDownload = g_pOptions->GetPauseDownload(); + bool pauseDownload = g_pOptions->GetPauseDownload(); - NZBInfo* pNZBInfo = NULL; + NZBInfo* nzbInfo = NULL; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo1 = *it; - if (pNZBInfo1->GetKind() == NZBInfo::nkUrl && - pNZBInfo1->GetUrlStatus() == NZBInfo::lsNone && - pNZBInfo1->GetDeleteStatus() == NZBInfo::dsNone && - (!bPauseDownload || g_pOptions->GetUrlForce()) && - (!pNZBInfo || pNZBInfo1->GetPriority() > pNZBInfo->GetPriority())) + NZBInfo* nzbInfo1 = *it; + if (nzbInfo1->GetKind() == NZBInfo::nkUrl && + nzbInfo1->GetUrlStatus() == NZBInfo::lsNone && + nzbInfo1->GetDeleteStatus() == NZBInfo::dsNone && + (!pauseDownload || g_pOptions->GetUrlForce()) && + (!nzbInfo || nzbInfo1->GetPriority() > nzbInfo->GetPriority())) { - pNZBInfo = pNZBInfo1; + nzbInfo = nzbInfo1; } } - return pNZBInfo; + return nzbInfo; } -void UrlCoordinator::StartUrlDownload(NZBInfo* pNZBInfo) +void UrlCoordinator::StartUrlDownload(NZBInfo* nzbInfo) { debug("Starting new UrlDownloader"); - UrlDownloader* pUrlDownloader = new UrlDownloader(); - pUrlDownloader->SetAutoDestroy(true); - pUrlDownloader->Attach(this); - pUrlDownloader->SetNZBInfo(pNZBInfo); - pUrlDownloader->SetURL(pNZBInfo->GetURL()); - pUrlDownloader->SetForce(g_pOptions->GetUrlForce()); - pNZBInfo->SetActiveDownloads(1); + UrlDownloader* urlDownloader = new UrlDownloader(); + urlDownloader->SetAutoDestroy(true); + urlDownloader->Attach(this); + urlDownloader->SetNZBInfo(nzbInfo); + urlDownloader->SetURL(nzbInfo->GetURL()); + urlDownloader->SetForce(g_pOptions->GetUrlForce()); + nzbInfo->SetActiveDownloads(1); char tmp[1024]; - pNZBInfo->MakeNiceUrlName(pNZBInfo->GetURL(), pNZBInfo->GetFilename(), tmp, 1024); - pUrlDownloader->SetInfoName(tmp); + nzbInfo->MakeNiceUrlName(nzbInfo->GetURL(), nzbInfo->GetFilename(), tmp, 1024); + urlDownloader->SetInfoName(tmp); - snprintf(tmp, 1024, "%surl-%i.tmp", g_pOptions->GetTempDir(), pNZBInfo->GetID()); + snprintf(tmp, 1024, "%surl-%i.tmp", g_pOptions->GetTempDir(), nzbInfo->GetID()); tmp[1024-1] = '\0'; - pUrlDownloader->SetOutputFilename(tmp); + urlDownloader->SetOutputFilename(tmp); - pNZBInfo->SetUrlStatus(NZBInfo::lsRunning); + nzbInfo->SetUrlStatus(NZBInfo::lsRunning); - m_ActiveDownloads.push_back(pUrlDownloader); - pUrlDownloader->Start(); + m_activeDownloads.push_back(urlDownloader); + urlDownloader->Start(); } -void UrlCoordinator::Update(Subject* pCaller, void* pAspect) +void UrlCoordinator::Update(Subject* caller, void* aspect) { debug("Notification from UrlDownloader received"); - UrlDownloader* pUrlDownloader = (UrlDownloader*) pCaller; - if ((pUrlDownloader->GetStatus() == WebDownloader::adFinished) || - (pUrlDownloader->GetStatus() == WebDownloader::adFailed) || - (pUrlDownloader->GetStatus() == WebDownloader::adRetry)) + UrlDownloader* urlDownloader = (UrlDownloader*) caller; + if ((urlDownloader->GetStatus() == WebDownloader::adFinished) || + (urlDownloader->GetStatus() == WebDownloader::adFailed) || + (urlDownloader->GetStatus() == WebDownloader::adRetry)) { - UrlCompleted(pUrlDownloader); + UrlCompleted(urlDownloader); } } -void UrlCoordinator::UrlCompleted(UrlDownloader* pUrlDownloader) +void UrlCoordinator::UrlCompleted(UrlDownloader* urlDownloader) { debug("URL downloaded"); - NZBInfo* pNZBInfo = pUrlDownloader->GetNZBInfo(); + NZBInfo* nzbInfo = urlDownloader->GetNZBInfo(); char filename[1024]; - if (pUrlDownloader->GetOriginalFilename()) + if (urlDownloader->GetOriginalFilename()) { - strncpy(filename, pUrlDownloader->GetOriginalFilename(), 1024); + strncpy(filename, urlDownloader->GetOriginalFilename(), 1024); filename[1024-1] = '\0'; } else { - strncpy(filename, Util::BaseFileName(pNZBInfo->GetURL()), 1024); + strncpy(filename, Util::BaseFileName(nzbInfo->GetURL()), 1024); filename[1024-1] = '\0'; // TODO: decode URL escaping @@ -360,141 +360,141 @@ void UrlCoordinator::UrlCompleted(UrlDownloader* pUrlDownloader) debug("Filename: [%s]", filename); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); // delete Download from active jobs - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { UrlDownloader* pa = *it; - if (pa == pUrlDownloader) + if (pa == urlDownloader) { - m_ActiveDownloads.erase(it); + m_activeDownloads.erase(it); break; } } - pNZBInfo->SetActiveDownloads(0); + nzbInfo->SetActiveDownloads(0); - bool bRetry = pUrlDownloader->GetStatus() == WebDownloader::adRetry && !pNZBInfo->GetDeleting(); + bool retry = urlDownloader->GetStatus() == WebDownloader::adRetry && !nzbInfo->GetDeleting(); - if (pNZBInfo->GetDeleting()) + if (nzbInfo->GetDeleting()) { - pNZBInfo->SetDeleteStatus(NZBInfo::dsManual); - pNZBInfo->SetUrlStatus(NZBInfo::lsNone); - pNZBInfo->SetDeleting(false); + nzbInfo->SetDeleteStatus(NZBInfo::dsManual); + nzbInfo->SetUrlStatus(NZBInfo::lsNone); + nzbInfo->SetDeleting(false); } - else if (pUrlDownloader->GetStatus() == WebDownloader::adFinished) + else if (urlDownloader->GetStatus() == WebDownloader::adFinished) { - pNZBInfo->SetUrlStatus(NZBInfo::lsFinished); + nzbInfo->SetUrlStatus(NZBInfo::lsFinished); } - else if (pUrlDownloader->GetStatus() == WebDownloader::adFailed) + else if (urlDownloader->GetStatus() == WebDownloader::adFailed) { - pNZBInfo->SetUrlStatus(NZBInfo::lsFailed); + nzbInfo->SetUrlStatus(NZBInfo::lsFailed); } - else if (pUrlDownloader->GetStatus() == WebDownloader::adRetry) + else if (urlDownloader->GetStatus() == WebDownloader::adRetry) { - pNZBInfo->SetUrlStatus(NZBInfo::lsNone); + nzbInfo->SetUrlStatus(NZBInfo::lsNone); } - if (!bRetry) + if (!retry) { - DownloadQueue::Aspect aspect = { DownloadQueue::eaUrlCompleted, pDownloadQueue, pNZBInfo, NULL }; - pDownloadQueue->Notify(&aspect); + DownloadQueue::Aspect aspect = { DownloadQueue::eaUrlCompleted, downloadQueue, nzbInfo, NULL }; + downloadQueue->Notify(&aspect); } DownloadQueue::Unlock(); - if (bRetry) + if (retry) { return; } - if (pNZBInfo->GetUrlStatus() == NZBInfo::lsFinished) + if (nzbInfo->GetUrlStatus() == NZBInfo::lsFinished) { // add nzb-file to download queue - Scanner::EAddStatus eAddStatus = g_pScanner->AddExternalFile( - !Util::EmptyStr(pNZBInfo->GetFilename()) ? pNZBInfo->GetFilename() : filename, - !Util::EmptyStr(pNZBInfo->GetCategory()) ? pNZBInfo->GetCategory() : pUrlDownloader->GetCategory(), - pNZBInfo->GetPriority(), pNZBInfo->GetDupeKey(), pNZBInfo->GetDupeScore(), pNZBInfo->GetDupeMode(), - pNZBInfo->GetParameters(), false, pNZBInfo->GetAddUrlPaused(), pNZBInfo, - pUrlDownloader->GetOutputFilename(), NULL, 0, NULL); + Scanner::EAddStatus addStatus = g_pScanner->AddExternalFile( + !Util::EmptyStr(nzbInfo->GetFilename()) ? nzbInfo->GetFilename() : filename, + !Util::EmptyStr(nzbInfo->GetCategory()) ? nzbInfo->GetCategory() : urlDownloader->GetCategory(), + nzbInfo->GetPriority(), nzbInfo->GetDupeKey(), nzbInfo->GetDupeScore(), nzbInfo->GetDupeMode(), + nzbInfo->GetParameters(), false, nzbInfo->GetAddUrlPaused(), nzbInfo, + urlDownloader->GetOutputFilename(), NULL, 0, NULL); - if (eAddStatus == Scanner::asSuccess) + if (addStatus == Scanner::asSuccess) { // if scanner has successfully added nzb-file to queue, our pNZBInfo is // already removed from queue and destroyed return; } - pNZBInfo->SetUrlStatus(eAddStatus == Scanner::asFailed ? NZBInfo::lsScanFailed : NZBInfo::lsScanSkipped); + nzbInfo->SetUrlStatus(addStatus == Scanner::asFailed ? NZBInfo::lsScanFailed : NZBInfo::lsScanSkipped); } // the rest of function is only for failed URLs or for failed scans - g_pQueueScriptCoordinator->EnqueueScript(pNZBInfo, QueueScriptCoordinator::qeUrlCompleted); + g_pQueueScriptCoordinator->EnqueueScript(nzbInfo, QueueScriptCoordinator::qeUrlCompleted); - pDownloadQueue = DownloadQueue::Lock(); + downloadQueue = DownloadQueue::Lock(); // delete URL from queue - pDownloadQueue->GetQueue()->Remove(pNZBInfo); - bool bDeleteObj = true; + downloadQueue->GetQueue()->Remove(nzbInfo); + bool deleteObj = true; // add failed URL to history if (g_pOptions->GetKeepHistory() > 0 && - pNZBInfo->GetUrlStatus() != NZBInfo::lsFinished && - !pNZBInfo->GetAvoidHistory()) + nzbInfo->GetUrlStatus() != NZBInfo::lsFinished && + !nzbInfo->GetAvoidHistory()) { - HistoryInfo* pHistoryInfo = new HistoryInfo(pNZBInfo); - pHistoryInfo->SetTime(time(NULL)); - pDownloadQueue->GetHistory()->push_front(pHistoryInfo); - bDeleteObj = false; + HistoryInfo* historyInfo = new HistoryInfo(nzbInfo); + historyInfo->SetTime(time(NULL)); + downloadQueue->GetHistory()->push_front(historyInfo); + deleteObj = false; } - pDownloadQueue->Save(); + downloadQueue->Save(); DownloadQueue::Unlock(); - if (bDeleteObj) + if (deleteObj) { - g_pDiskState->DiscardFiles(pNZBInfo); - delete pNZBInfo; + g_pDiskState->DiscardFiles(nzbInfo); + delete nzbInfo; } } -bool UrlCoordinator::DeleteQueueEntry(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, bool bAvoidHistory) +bool UrlCoordinator::DeleteQueueEntry(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, bool avoidHistory) { - if (pNZBInfo->GetActiveDownloads() > 0) + if (nzbInfo->GetActiveDownloads() > 0) { - info("Deleting active URL %s", pNZBInfo->GetName()); - pNZBInfo->SetDeleting(true); - pNZBInfo->SetAvoidHistory(bAvoidHistory); + info("Deleting active URL %s", nzbInfo->GetName()); + nzbInfo->SetDeleting(true); + nzbInfo->SetAvoidHistory(avoidHistory); - for (ActiveDownloads::iterator it = m_ActiveDownloads.begin(); it != m_ActiveDownloads.end(); it++) + for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end(); it++) { - UrlDownloader* pUrlDownloader = *it; - if (pUrlDownloader->GetNZBInfo() == pNZBInfo) + UrlDownloader* urlDownloader = *it; + if (urlDownloader->GetNZBInfo() == nzbInfo) { - pUrlDownloader->Stop(); + urlDownloader->Stop(); return true; } } } - info("Deleting URL %s", pNZBInfo->GetName()); + info("Deleting URL %s", nzbInfo->GetName()); - pNZBInfo->SetDeleteStatus(NZBInfo::dsManual); - pNZBInfo->SetUrlStatus(NZBInfo::lsNone); + nzbInfo->SetDeleteStatus(NZBInfo::dsManual); + nzbInfo->SetUrlStatus(NZBInfo::lsNone); - pDownloadQueue->GetQueue()->Remove(pNZBInfo); - if (g_pOptions->GetKeepHistory() > 0 && !bAvoidHistory) + downloadQueue->GetQueue()->Remove(nzbInfo); + if (g_pOptions->GetKeepHistory() > 0 && !avoidHistory) { - HistoryInfo* pHistoryInfo = new HistoryInfo(pNZBInfo); - pHistoryInfo->SetTime(time(NULL)); - pDownloadQueue->GetHistory()->push_front(pHistoryInfo); + HistoryInfo* historyInfo = new HistoryInfo(nzbInfo); + historyInfo->SetTime(time(NULL)); + downloadQueue->GetHistory()->push_front(historyInfo); } else { - g_pDiskState->DiscardFiles(pNZBInfo); - delete pNZBInfo; + g_pDiskState->DiscardFiles(nzbInfo); + delete nzbInfo; } return true; diff --git a/daemon/queue/UrlCoordinator.h b/daemon/queue/UrlCoordinator.h index 36b289a6..6e6d6da4 100644 --- a/daemon/queue/UrlCoordinator.h +++ b/daemon/queue/UrlCoordinator.h @@ -44,13 +44,13 @@ private: typedef std::list ActiveDownloads; private: - ActiveDownloads m_ActiveDownloads; - bool m_bHasMoreJobs; - bool m_bForce; + ActiveDownloads m_activeDownloads; + bool m_hasMoreJobs; + bool m_force; - NZBInfo* GetNextUrl(DownloadQueue* pDownloadQueue); - void StartUrlDownload(NZBInfo* pNZBInfo); - void UrlCompleted(UrlDownloader* pUrlDownloader); + NZBInfo* GetNextUrl(DownloadQueue* downloadQueue); + void StartUrlDownload(NZBInfo* nzbInfo); + void UrlCompleted(UrlDownloader* urlDownloader); void ResetHangingDownloads(); protected: @@ -61,12 +61,12 @@ public: virtual ~UrlCoordinator(); virtual void Run(); virtual void Stop(); - void Update(Subject* pCaller, void* pAspect); + void Update(Subject* caller, void* aspect); // Editing the queue - void AddUrlToQueue(NZBInfo* pNZBInfo, bool bAddTop); - bool HasMoreJobs() { return m_bHasMoreJobs; } - bool DeleteQueueEntry(DownloadQueue* pDownloadQueue, NZBInfo* pNZBInfo, bool bAvoidHistory); + void AddUrlToQueue(NZBInfo* nzbInfo, bool addTop); + bool HasMoreJobs() { return m_hasMoreJobs; } + bool DeleteQueueEntry(DownloadQueue* downloadQueue, NZBInfo* nzbInfo, bool avoidHistory); }; extern UrlCoordinator* g_pUrlCoordinator; @@ -74,18 +74,18 @@ extern UrlCoordinator* g_pUrlCoordinator; class UrlDownloader : public WebDownloader { private: - NZBInfo* m_pNZBInfo; - char* m_szCategory; + NZBInfo* m_nzbInfo; + char* m_category; protected: - virtual void ProcessHeader(const char* szLine); + virtual void ProcessHeader(const char* line); public: UrlDownloader(); ~UrlDownloader(); - void SetNZBInfo(NZBInfo* pNZBInfo) { m_pNZBInfo = pNZBInfo; } - NZBInfo* GetNZBInfo() { return m_pNZBInfo; } - const char* GetCategory() { return m_szCategory; } + void SetNZBInfo(NZBInfo* nzbInfo) { m_nzbInfo = nzbInfo; } + NZBInfo* GetNZBInfo() { return m_nzbInfo; } + const char* GetCategory() { return m_category; } }; #endif diff --git a/daemon/remote/BinRpc.cpp b/daemon/remote/BinRpc.cpp index 917cd2b0..cb6bd9af 100644 --- a/daemon/remote/BinRpc.cpp +++ b/daemon/remote/BinRpc.cpp @@ -83,17 +83,17 @@ const unsigned int g_iMessageRequestSizes[] = class BinCommand { protected: - Connection* m_pConnection; - SNZBRequestBase* m_pMessageBase; + Connection* m_connection; + SNZBRequestBase* m_messageBase; - bool ReceiveRequest(void* pBuffer, int iSize); - void SendBoolResponse(bool bSuccess, const char* szText); + bool ReceiveRequest(void* buffer, int size); + void SendBoolResponse(bool success, const char* text); public: virtual ~BinCommand() {} virtual void Execute() = 0; - void SetConnection(Connection* pConnection) { m_pConnection = pConnection; } - void SetMessageBase(SNZBRequestBase* pMessageBase) { m_pMessageBase = pMessageBase; } + void SetConnection(Connection* connection) { m_connection = connection; } + void SetMessageBase(SNZBRequestBase* messageBase) { m_messageBase = messageBase; } }; class DownloadBinCommand: public BinCommand @@ -192,110 +192,110 @@ public: BinRpcProcessor::BinRpcProcessor() { - m_MessageBase.m_iSignature = (int)NZBMESSAGE_SIGNATURE; + m_messageBase.m_signature = (int)NZBMESSAGE_SIGNATURE; } void BinRpcProcessor::Execute() { // Read the first package which needs to be a request - if (!m_pConnection->Recv(((char*)&m_MessageBase) + sizeof(m_MessageBase.m_iSignature), sizeof(m_MessageBase) - sizeof(m_MessageBase.m_iSignature))) + if (!m_connection->Recv(((char*)&m_messageBase) + sizeof(m_messageBase.m_signature), sizeof(m_messageBase) - sizeof(m_messageBase.m_signature))) { - warn("Non-nzbget request received on port %i from %s", g_pOptions->GetControlPort(), m_pConnection->GetRemoteAddr()); + warn("Non-nzbget request received on port %i from %s", g_pOptions->GetControlPort(), m_connection->GetRemoteAddr()); return; } - if ((strlen(g_pOptions->GetControlUsername()) > 0 && strcmp(m_MessageBase.m_szUsername, g_pOptions->GetControlUsername())) || - strcmp(m_MessageBase.m_szPassword, g_pOptions->GetControlPassword())) + if ((strlen(g_pOptions->GetControlUsername()) > 0 && strcmp(m_messageBase.m_username, g_pOptions->GetControlUsername())) || + strcmp(m_messageBase.m_password, g_pOptions->GetControlPassword())) { - warn("nzbget request received on port %i from %s, but username or password invalid", g_pOptions->GetControlPort(), m_pConnection->GetRemoteAddr()); + warn("nzbget request received on port %i from %s, but username or password invalid", g_pOptions->GetControlPort(), m_connection->GetRemoteAddr()); return; } - debug("%s request received from %s", g_szMessageRequestNames[ntohl(m_MessageBase.m_iType)], m_pConnection->GetRemoteAddr()); + debug("%s request received from %s", g_szMessageRequestNames[ntohl(m_messageBase.m_type)], m_connection->GetRemoteAddr()); Dispatch(); } void BinRpcProcessor::Dispatch() { - if (ntohl(m_MessageBase.m_iType) >= (int)eRemoteRequestDownload && - ntohl(m_MessageBase.m_iType) <= (int)eRemoteRequestHistory && - g_iMessageRequestSizes[ntohl(m_MessageBase.m_iType)] != ntohl(m_MessageBase.m_iStructSize)) + if (ntohl(m_messageBase.m_type) >= (int)remoteRequestDownload && + ntohl(m_messageBase.m_type) <= (int)remoteRequestHistory && + g_iMessageRequestSizes[ntohl(m_messageBase.m_type)] != ntohl(m_messageBase.m_structSize)) { error("Invalid size of request: expected %i Bytes, but received %i Bytes", - g_iMessageRequestSizes[ntohl(m_MessageBase.m_iType)], ntohl(m_MessageBase.m_iStructSize)); + g_iMessageRequestSizes[ntohl(m_messageBase.m_type)], ntohl(m_messageBase.m_structSize)); return; } BinCommand* command = NULL; - switch (ntohl(m_MessageBase.m_iType)) + switch (ntohl(m_messageBase.m_type)) { - case eRemoteRequestDownload: + case remoteRequestDownload: command = new DownloadBinCommand(); break; - case eRemoteRequestList: + case remoteRequestList: command = new ListBinCommand(); break; - case eRemoteRequestLog: + case remoteRequestLog: command = new LogBinCommand(); break; - case eRemoteRequestPauseUnpause: + case remoteRequestPauseUnpause: command = new PauseUnpauseBinCommand(); break; - case eRemoteRequestEditQueue: + case remoteRequestEditQueue: command = new EditQueueBinCommand(); break; - case eRemoteRequestSetDownloadRate: + case remoteRequestSetDownloadRate: command = new SetDownloadRateBinCommand(); break; - case eRemoteRequestDumpDebug: + case remoteRequestDumpDebug: command = new DumpDebugBinCommand(); break; - case eRemoteRequestShutdown: + case remoteRequestShutdown: command = new ShutdownBinCommand(); break; - case eRemoteRequestReload: + case remoteRequestReload: command = new ReloadBinCommand(); break; - case eRemoteRequestVersion: + case remoteRequestVersion: command = new VersionBinCommand(); break; - case eRemoteRequestPostQueue: + case remoteRequestPostQueue: command = new PostQueueBinCommand(); break; - case eRemoteRequestWriteLog: + case remoteRequestWriteLog: command = new WriteLogBinCommand(); break; - case eRemoteRequestScan: + case remoteRequestScan: command = new ScanBinCommand(); break; - case eRemoteRequestHistory: + case remoteRequestHistory: command = new HistoryBinCommand(); break; default: - error("Received unsupported request %i", ntohl(m_MessageBase.m_iType)); + error("Received unsupported request %i", ntohl(m_messageBase.m_type)); break; } if (command) { - command->SetConnection(m_pConnection); - command->SetMessageBase(&m_MessageBase); + command->SetConnection(m_connection); + command->SetMessageBase(&m_messageBase); command->Execute(); delete command; } @@ -304,29 +304,29 @@ void BinRpcProcessor::Dispatch() //***************************************************************** // Commands -void BinCommand::SendBoolResponse(bool bSuccess, const char* szText) +void BinCommand::SendBoolResponse(bool success, const char* text) { // all bool-responses have the same format of structure, we use SNZBDownloadResponse here SNZBDownloadResponse BoolResponse; memset(&BoolResponse, 0, sizeof(BoolResponse)); - BoolResponse.m_MessageBase.m_iSignature = htonl(NZBMESSAGE_SIGNATURE); - BoolResponse.m_MessageBase.m_iStructSize = htonl(sizeof(BoolResponse)); - BoolResponse.m_bSuccess = htonl(bSuccess); - int iTextLen = strlen(szText) + 1; - BoolResponse.m_iTrailingDataLength = htonl(iTextLen); + BoolResponse.m_messageBase.m_signature = htonl(NZBMESSAGE_SIGNATURE); + BoolResponse.m_messageBase.m_structSize = htonl(sizeof(BoolResponse)); + BoolResponse.m_success = htonl(success); + int textLen = strlen(text) + 1; + BoolResponse.m_trailingDataLength = htonl(textLen); // Send the request answer - m_pConnection->Send((char*) &BoolResponse, sizeof(BoolResponse)); - m_pConnection->Send((char*)szText, iTextLen); + m_connection->Send((char*) &BoolResponse, sizeof(BoolResponse)); + m_connection->Send((char*)text, textLen); } -bool BinCommand::ReceiveRequest(void* pBuffer, int iSize) +bool BinCommand::ReceiveRequest(void* buffer, int size) { - memcpy(pBuffer, m_pMessageBase, sizeof(SNZBRequestBase)); - iSize -= sizeof(SNZBRequestBase); - if (iSize > 0) + memcpy(buffer, m_messageBase, sizeof(SNZBRequestBase)); + size -= sizeof(SNZBRequestBase); + if (size > 0) { - if (!m_pConnection->Recv(((char*)pBuffer) + sizeof(SNZBRequestBase), iSize)) + if (!m_connection->Recv(((char*)buffer) + sizeof(SNZBRequestBase), size)) { error("invalid request"); return false; @@ -345,18 +345,18 @@ void PauseUnpauseBinCommand::Execute() g_pOptions->SetResumeTime(0); - switch (ntohl(PauseUnpauseRequest.m_iAction)) + switch (ntohl(PauseUnpauseRequest.m_action)) { - case eRemotePauseUnpauseActionDownload: - g_pOptions->SetPauseDownload(ntohl(PauseUnpauseRequest.m_bPause)); + case remotePauseUnpauseActionDownload: + g_pOptions->SetPauseDownload(ntohl(PauseUnpauseRequest.m_pause)); break; - case eRemotePauseUnpauseActionPostProcess: - g_pOptions->SetPausePostProcess(ntohl(PauseUnpauseRequest.m_bPause)); + case remotePauseUnpauseActionPostProcess: + g_pOptions->SetPausePostProcess(ntohl(PauseUnpauseRequest.m_pause)); break; - case eRemotePauseUnpauseActionScan: - g_pOptions->SetPauseScan(ntohl(PauseUnpauseRequest.m_bPause)); + case remotePauseUnpauseActionScan: + g_pOptions->SetPauseScan(ntohl(PauseUnpauseRequest.m_pause)); break; } @@ -371,7 +371,7 @@ void SetDownloadRateBinCommand::Execute() return; } - g_pOptions->SetDownloadRate(ntohl(SetDownloadRequest.m_iDownloadRate)); + g_pOptions->SetDownloadRate(ntohl(SetDownloadRequest.m_downloadRate)); SendBoolResponse(true, "Rate-Command completed successfully"); } @@ -430,60 +430,60 @@ void DownloadBinCommand::Execute() return; } - int iBufLen = ntohl(DownloadRequest.m_iTrailingDataLength); - char* szNZBContent = (char*)malloc(iBufLen); + int bufLen = ntohl(DownloadRequest.m_trailingDataLength); + char* nzbContent = (char*)malloc(bufLen); - if (!m_pConnection->Recv(szNZBContent, iBufLen)) + if (!m_connection->Recv(nzbContent, bufLen)) { error("invalid request"); - free(szNZBContent); + free(nzbContent); return; } - int iPriority = ntohl(DownloadRequest.m_iPriority); - bool bAddPaused = ntohl(DownloadRequest.m_bAddPaused); - bool bAddTop = ntohl(DownloadRequest.m_bAddFirst); - int iDupeMode = ntohl(DownloadRequest.m_iDupeMode); - int iDupeScore = ntohl(DownloadRequest.m_iDupeScore); + int priority = ntohl(DownloadRequest.m_priority); + bool addPaused = ntohl(DownloadRequest.m_addPaused); + bool addTop = ntohl(DownloadRequest.m_addFirst); + int dupeMode = ntohl(DownloadRequest.m_dupeMode); + int dupeScore = ntohl(DownloadRequest.m_dupeScore); - bool bOK = false; + bool ok = false; - if (!strncasecmp(szNZBContent, "http://", 6) || !strncasecmp(szNZBContent, "https://", 7)) + if (!strncasecmp(nzbContent, "http://", 6) || !strncasecmp(nzbContent, "https://", 7)) { // add url - NZBInfo* pNZBInfo = new NZBInfo(); - pNZBInfo->SetKind(NZBInfo::nkUrl); - pNZBInfo->SetURL(szNZBContent); - pNZBInfo->SetFilename(DownloadRequest.m_szNZBFilename); - pNZBInfo->SetCategory(DownloadRequest.m_szCategory); - pNZBInfo->SetPriority(iPriority); - pNZBInfo->SetAddUrlPaused(bAddPaused); - pNZBInfo->SetDupeKey(DownloadRequest.m_szDupeKey); - pNZBInfo->SetDupeScore(iDupeScore); - pNZBInfo->SetDupeMode((EDupeMode)iDupeMode); + NZBInfo* nzbInfo = new NZBInfo(); + nzbInfo->SetKind(NZBInfo::nkUrl); + nzbInfo->SetURL(nzbContent); + nzbInfo->SetFilename(DownloadRequest.m_nzbFilename); + nzbInfo->SetCategory(DownloadRequest.m_category); + nzbInfo->SetPriority(priority); + nzbInfo->SetAddUrlPaused(addPaused); + nzbInfo->SetDupeKey(DownloadRequest.m_dupeKey); + nzbInfo->SetDupeScore(dupeScore); + nzbInfo->SetDupeMode((EDupeMode)dupeMode); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - pDownloadQueue->GetQueue()->Add(pNZBInfo, bAddTop); - pDownloadQueue->Save(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + downloadQueue->GetQueue()->Add(nzbInfo, addTop); + downloadQueue->Save(); DownloadQueue::Unlock(); - bOK = true; + ok = true; } else { - bOK = g_pScanner->AddExternalFile(DownloadRequest.m_szNZBFilename, DownloadRequest.m_szCategory, iPriority, - DownloadRequest.m_szDupeKey, iDupeScore, (EDupeMode)iDupeMode, NULL, bAddTop, bAddPaused, - NULL, NULL, szNZBContent, iBufLen, NULL) != Scanner::asFailed; + ok = g_pScanner->AddExternalFile(DownloadRequest.m_nzbFilename, DownloadRequest.m_category, priority, + DownloadRequest.m_dupeKey, dupeScore, (EDupeMode)dupeMode, NULL, addTop, addPaused, + NULL, NULL, nzbContent, bufLen, NULL) != Scanner::asFailed; } char tmp[1024]; - snprintf(tmp, 1024, bOK ? "Collection %s added to queue" : "Download Request failed for %s", - Util::BaseFileName(DownloadRequest.m_szNZBFilename)); + snprintf(tmp, 1024, ok ? "Collection %s added to queue" : "Download Request failed for %s", + Util::BaseFileName(DownloadRequest.m_nzbFilename)); tmp[1024-1] = '\0'; - SendBoolResponse(bOK, tmp); + SendBoolResponse(ok, tmp); - free(szNZBContent); + free(nzbContent); } void ListBinCommand::Execute() @@ -496,70 +496,70 @@ void ListBinCommand::Execute() SNZBListResponse ListResponse; memset(&ListResponse, 0, sizeof(ListResponse)); - ListResponse.m_MessageBase.m_iSignature = htonl(NZBMESSAGE_SIGNATURE); - ListResponse.m_MessageBase.m_iStructSize = htonl(sizeof(ListResponse)); - ListResponse.m_iEntrySize = htonl(sizeof(SNZBListResponseFileEntry)); - ListResponse.m_bRegExValid = 0; + ListResponse.m_messageBase.m_signature = htonl(NZBMESSAGE_SIGNATURE); + ListResponse.m_messageBase.m_structSize = htonl(sizeof(ListResponse)); + ListResponse.m_entrySize = htonl(sizeof(SNZBListResponseFileEntry)); + ListResponse.m_regExValid = 0; char* buf = NULL; int bufsize = 0; - if (ntohl(ListRequest.m_bFileList)) + if (ntohl(ListRequest.m_fileList)) { - eRemoteMatchMode eMatchMode = (eRemoteMatchMode)ntohl(ListRequest.m_iMatchMode); - bool bMatchGroup = ntohl(ListRequest.m_bMatchGroup); - const char* szPattern = ListRequest.m_szPattern; + remoteMatchMode matchMode = (remoteMatchMode)ntohl(ListRequest.m_matchMode); + bool matchGroup = ntohl(ListRequest.m_matchGroup); + const char* pattern = ListRequest.m_pattern; - RegEx *pRegEx = NULL; - if (eMatchMode == eRemoteMatchModeRegEx) + RegEx *regEx = NULL; + if (matchMode == remoteMatchModeRegEx) { - pRegEx = new RegEx(szPattern); - ListResponse.m_bRegExValid = pRegEx->IsValid(); + regEx = new RegEx(pattern); + ListResponse.m_regExValid = regEx->IsValid(); } // Make a data structure and copy all the elements of the list into it - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); // calculate required buffer size for nzbs - int iNrNZBEntries = pDownloadQueue->GetQueue()->size(); - int iNrPPPEntries = 0; - bufsize += iNrNZBEntries * sizeof(SNZBListResponseNZBEntry); - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + int nrNzbEntries = downloadQueue->GetQueue()->size(); + int nrPPPEntries = 0; + bufsize += nrNzbEntries * sizeof(SNZBListResponseNZBEntry); + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - bufsize += strlen(pNZBInfo->GetFilename()) + 1; - bufsize += strlen(pNZBInfo->GetName()) + 1; - bufsize += strlen(pNZBInfo->GetDestDir()) + 1; - bufsize += strlen(pNZBInfo->GetCategory()) + 1; - bufsize += strlen(pNZBInfo->GetQueuedFilename()) + 1; + NZBInfo* nzbInfo = *it; + bufsize += strlen(nzbInfo->GetFilename()) + 1; + bufsize += strlen(nzbInfo->GetName()) + 1; + bufsize += strlen(nzbInfo->GetDestDir()) + 1; + bufsize += strlen(nzbInfo->GetCategory()) + 1; + bufsize += strlen(nzbInfo->GetQueuedFilename()) + 1; // align struct to 4-bytes, needed by ARM-processor (and may be others) bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0; // calculate required buffer size for pp-parameters - for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++) + for (NZBParameterList::iterator it = nzbInfo->GetParameters()->begin(); it != nzbInfo->GetParameters()->end(); it++) { - NZBParameter* pNZBParameter = *it; + NZBParameter* nzbParameter = *it; bufsize += sizeof(SNZBListResponsePPPEntry); - bufsize += strlen(pNZBParameter->GetName()) + 1; - bufsize += strlen(pNZBParameter->GetValue()) + 1; + bufsize += strlen(nzbParameter->GetName()) + 1; + bufsize += strlen(nzbParameter->GetValue()) + 1; // align struct to 4-bytes, needed by ARM-processor (and may be others) bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0; - iNrPPPEntries++; + nrPPPEntries++; } } // calculate required buffer size for files - int iNrFileEntries = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + int nrFileEntries = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; - iNrFileEntries++; + FileInfo* fileInfo = *it2; + nrFileEntries++; bufsize += sizeof(SNZBListResponseFileEntry); - bufsize += strlen(pFileInfo->GetSubject()) + 1; - bufsize += strlen(pFileInfo->GetFilename()) + 1; + bufsize += strlen(fileInfo->GetSubject()) + 1; + bufsize += strlen(fileInfo->GetFilename()) + 1; // align struct to 4-bytes, needed by ARM-processor (and may be others) bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0; } @@ -569,75 +569,75 @@ void ListBinCommand::Execute() char* bufptr = buf; // write nzb entries - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; + NZBInfo* nzbInfo = *it; - SNZBListResponseNZBEntry* pListAnswer = (SNZBListResponseNZBEntry*) bufptr; + SNZBListResponseNZBEntry* listAnswer = (SNZBListResponseNZBEntry*) bufptr; - unsigned long iSizeHi, iSizeLo, iRemainingSizeHi, iRemainingSizeLo, iPausedSizeHi, iPausedSizeLo; - Util::SplitInt64(pNZBInfo->GetSize(), &iSizeHi, &iSizeLo); - Util::SplitInt64(pNZBInfo->GetRemainingSize(), &iRemainingSizeHi, &iRemainingSizeLo); - Util::SplitInt64(pNZBInfo->GetPausedSize(), &iPausedSizeHi, &iPausedSizeLo); + unsigned long sizeHi, sizeLo, remainingSizeHi, remainingSizeLo, pausedSizeHi, pausedSizeLo; + Util::SplitInt64(nzbInfo->GetSize(), &sizeHi, &sizeLo); + Util::SplitInt64(nzbInfo->GetRemainingSize(), &remainingSizeHi, &remainingSizeLo); + Util::SplitInt64(nzbInfo->GetPausedSize(), &pausedSizeHi, &pausedSizeLo); - pListAnswer->m_iID = htonl(pNZBInfo->GetID()); - pListAnswer->m_iKind = htonl(pNZBInfo->GetKind()); - pListAnswer->m_iSizeLo = htonl(iSizeLo); - pListAnswer->m_iSizeHi = htonl(iSizeHi); - pListAnswer->m_iRemainingSizeLo = htonl(iRemainingSizeLo); - pListAnswer->m_iRemainingSizeHi = htonl(iRemainingSizeHi); - pListAnswer->m_iPausedSizeLo = htonl(iPausedSizeLo); - pListAnswer->m_iPausedSizeHi = htonl(iPausedSizeHi); - pListAnswer->m_iPausedCount = htonl(pNZBInfo->GetPausedFileCount()); - pListAnswer->m_iRemainingParCount = htonl(pNZBInfo->GetRemainingParCount()); - pListAnswer->m_iPriority = htonl(pNZBInfo->GetPriority()); - pListAnswer->m_bMatch = htonl(bMatchGroup && (!pRegEx || pRegEx->Match(pNZBInfo->GetName()))); - pListAnswer->m_iFilenameLen = htonl(strlen(pNZBInfo->GetFilename()) + 1); - pListAnswer->m_iNameLen = htonl(strlen(pNZBInfo->GetName()) + 1); - pListAnswer->m_iDestDirLen = htonl(strlen(pNZBInfo->GetDestDir()) + 1); - pListAnswer->m_iCategoryLen = htonl(strlen(pNZBInfo->GetCategory()) + 1); - pListAnswer->m_iQueuedFilenameLen = htonl(strlen(pNZBInfo->GetQueuedFilename()) + 1); + listAnswer->m_id = htonl(nzbInfo->GetID()); + listAnswer->m_kind = htonl(nzbInfo->GetKind()); + listAnswer->m_sizeLo = htonl(sizeLo); + listAnswer->m_sizeHi = htonl(sizeHi); + listAnswer->m_remainingSizeLo = htonl(remainingSizeLo); + listAnswer->m_remainingSizeHi = htonl(remainingSizeHi); + listAnswer->m_pausedSizeLo = htonl(pausedSizeLo); + listAnswer->m_pausedSizeHi = htonl(pausedSizeHi); + listAnswer->m_pausedCount = htonl(nzbInfo->GetPausedFileCount()); + listAnswer->m_remainingParCount = htonl(nzbInfo->GetRemainingParCount()); + listAnswer->m_priority = htonl(nzbInfo->GetPriority()); + listAnswer->m_match = htonl(matchGroup && (!regEx || regEx->Match(nzbInfo->GetName()))); + listAnswer->m_filenameLen = htonl(strlen(nzbInfo->GetFilename()) + 1); + listAnswer->m_nameLen = htonl(strlen(nzbInfo->GetName()) + 1); + listAnswer->m_destDirLen = htonl(strlen(nzbInfo->GetDestDir()) + 1); + listAnswer->m_categoryLen = htonl(strlen(nzbInfo->GetCategory()) + 1); + listAnswer->m_queuedFilenameLen = htonl(strlen(nzbInfo->GetQueuedFilename()) + 1); bufptr += sizeof(SNZBListResponseNZBEntry); - strcpy(bufptr, pNZBInfo->GetFilename()); - bufptr += ntohl(pListAnswer->m_iFilenameLen); - strcpy(bufptr, pNZBInfo->GetName()); - bufptr += ntohl(pListAnswer->m_iNameLen); - strcpy(bufptr, pNZBInfo->GetDestDir()); - bufptr += ntohl(pListAnswer->m_iDestDirLen); - strcpy(bufptr, pNZBInfo->GetCategory()); - bufptr += ntohl(pListAnswer->m_iCategoryLen); - strcpy(bufptr, pNZBInfo->GetQueuedFilename()); - bufptr += ntohl(pListAnswer->m_iQueuedFilenameLen); + strcpy(bufptr, nzbInfo->GetFilename()); + bufptr += ntohl(listAnswer->m_filenameLen); + strcpy(bufptr, nzbInfo->GetName()); + bufptr += ntohl(listAnswer->m_nameLen); + strcpy(bufptr, nzbInfo->GetDestDir()); + bufptr += ntohl(listAnswer->m_destDirLen); + strcpy(bufptr, nzbInfo->GetCategory()); + bufptr += ntohl(listAnswer->m_categoryLen); + strcpy(bufptr, nzbInfo->GetQueuedFilename()); + bufptr += ntohl(listAnswer->m_queuedFilenameLen); // align struct to 4-bytes, needed by ARM-processor (and may be others) if ((size_t)bufptr % 4 > 0) { - pListAnswer->m_iQueuedFilenameLen = htonl(ntohl(pListAnswer->m_iQueuedFilenameLen) + 4 - (size_t)bufptr % 4); + listAnswer->m_queuedFilenameLen = htonl(ntohl(listAnswer->m_queuedFilenameLen) + 4 - (size_t)bufptr % 4); memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data" bufptr += 4 - (size_t)bufptr % 4; } } // write ppp entries - int iNZBIndex = 1; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++, iNZBIndex++) + int nzbIndex = 1; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++, nzbIndex++) { - NZBInfo* pNZBInfo = *it; - for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++) + NZBInfo* nzbInfo = *it; + for (NZBParameterList::iterator it = nzbInfo->GetParameters()->begin(); it != nzbInfo->GetParameters()->end(); it++) { - NZBParameter* pNZBParameter = *it; - SNZBListResponsePPPEntry* pListAnswer = (SNZBListResponsePPPEntry*) bufptr; - pListAnswer->m_iNZBIndex = htonl(iNZBIndex); - pListAnswer->m_iNameLen = htonl(strlen(pNZBParameter->GetName()) + 1); - pListAnswer->m_iValueLen = htonl(strlen(pNZBParameter->GetValue()) + 1); + NZBParameter* nzbParameter = *it; + SNZBListResponsePPPEntry* listAnswer = (SNZBListResponsePPPEntry*) bufptr; + listAnswer->m_nzbIndex = htonl(nzbIndex); + listAnswer->m_nameLen = htonl(strlen(nzbParameter->GetName()) + 1); + listAnswer->m_valueLen = htonl(strlen(nzbParameter->GetValue()) + 1); bufptr += sizeof(SNZBListResponsePPPEntry); - strcpy(bufptr, pNZBParameter->GetName()); - bufptr += ntohl(pListAnswer->m_iNameLen); - strcpy(bufptr, pNZBParameter->GetValue()); - bufptr += ntohl(pListAnswer->m_iValueLen); + strcpy(bufptr, nzbParameter->GetName()); + bufptr += ntohl(listAnswer->m_nameLen); + strcpy(bufptr, nzbParameter->GetValue()); + bufptr += ntohl(listAnswer->m_valueLen); // align struct to 4-bytes, needed by ARM-processor (and may be others) if ((size_t)bufptr % 4 > 0) { - pListAnswer->m_iValueLen = htonl(ntohl(pListAnswer->m_iValueLen) + 4 - (size_t)bufptr % 4); + listAnswer->m_valueLen = htonl(ntohl(listAnswer->m_valueLen) + 4 - (size_t)bufptr % 4); memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data" bufptr += 4 - (size_t)bufptr % 4; } @@ -645,55 +645,55 @@ void ListBinCommand::Execute() } // write file entries - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; + FileInfo* fileInfo = *it2; - unsigned long iSizeHi, iSizeLo; - SNZBListResponseFileEntry* pListAnswer = (SNZBListResponseFileEntry*) bufptr; - pListAnswer->m_iID = htonl(pFileInfo->GetID()); + unsigned long sizeHi, sizeLo; + SNZBListResponseFileEntry* listAnswer = (SNZBListResponseFileEntry*) bufptr; + listAnswer->m_id = htonl(fileInfo->GetID()); - int iNZBIndex = 0; - for (unsigned int i = 0; i < pDownloadQueue->GetQueue()->size(); i++) + int nzbIndex = 0; + for (unsigned int i = 0; i < downloadQueue->GetQueue()->size(); i++) { - iNZBIndex++; - if (pDownloadQueue->GetQueue()->at(i) == pFileInfo->GetNZBInfo()) + nzbIndex++; + if (downloadQueue->GetQueue()->at(i) == fileInfo->GetNZBInfo()) { break; } } - pListAnswer->m_iNZBIndex = htonl(iNZBIndex); + listAnswer->m_nzbIndex = htonl(nzbIndex); - if (pRegEx && !bMatchGroup) + if (regEx && !matchGroup) { - char szFilename[MAX_PATH]; - snprintf(szFilename, sizeof(szFilename) - 1, "%s/%s", pFileInfo->GetNZBInfo()->GetName(), Util::BaseFileName(pFileInfo->GetFilename())); - pListAnswer->m_bMatch = htonl(pRegEx->Match(szFilename)); + char filename[MAX_PATH]; + snprintf(filename, sizeof(filename) - 1, "%s/%s", fileInfo->GetNZBInfo()->GetName(), Util::BaseFileName(fileInfo->GetFilename())); + listAnswer->m_match = htonl(regEx->Match(filename)); } - Util::SplitInt64(pFileInfo->GetSize(), &iSizeHi, &iSizeLo); - pListAnswer->m_iFileSizeLo = htonl(iSizeLo); - pListAnswer->m_iFileSizeHi = htonl(iSizeHi); - Util::SplitInt64(pFileInfo->GetRemainingSize(), &iSizeHi, &iSizeLo); - pListAnswer->m_iRemainingSizeLo = htonl(iSizeLo); - pListAnswer->m_iRemainingSizeHi = htonl(iSizeHi); - pListAnswer->m_bFilenameConfirmed = htonl(pFileInfo->GetFilenameConfirmed()); - pListAnswer->m_bPaused = htonl(pFileInfo->GetPaused()); - pListAnswer->m_iActiveDownloads = htonl(pFileInfo->GetActiveDownloads()); - pListAnswer->m_iSubjectLen = htonl(strlen(pFileInfo->GetSubject()) + 1); - pListAnswer->m_iFilenameLen = htonl(strlen(pFileInfo->GetFilename()) + 1); + Util::SplitInt64(fileInfo->GetSize(), &sizeHi, &sizeLo); + listAnswer->m_fileSizeLo = htonl(sizeLo); + listAnswer->m_fileSizeHi = htonl(sizeHi); + Util::SplitInt64(fileInfo->GetRemainingSize(), &sizeHi, &sizeLo); + listAnswer->m_remainingSizeLo = htonl(sizeLo); + listAnswer->m_remainingSizeHi = htonl(sizeHi); + listAnswer->m_filenameConfirmed = htonl(fileInfo->GetFilenameConfirmed()); + listAnswer->m_paused = htonl(fileInfo->GetPaused()); + listAnswer->m_activeDownloads = htonl(fileInfo->GetActiveDownloads()); + listAnswer->m_subjectLen = htonl(strlen(fileInfo->GetSubject()) + 1); + listAnswer->m_filenameLen = htonl(strlen(fileInfo->GetFilename()) + 1); bufptr += sizeof(SNZBListResponseFileEntry); - strcpy(bufptr, pFileInfo->GetSubject()); - bufptr += ntohl(pListAnswer->m_iSubjectLen); - strcpy(bufptr, pFileInfo->GetFilename()); - bufptr += ntohl(pListAnswer->m_iFilenameLen); + strcpy(bufptr, fileInfo->GetSubject()); + bufptr += ntohl(listAnswer->m_subjectLen); + strcpy(bufptr, fileInfo->GetFilename()); + bufptr += ntohl(listAnswer->m_filenameLen); // align struct to 4-bytes, needed by ARM-processor (and may be others) if ((size_t)bufptr % 4 > 0) { - pListAnswer->m_iFilenameLen = htonl(ntohl(pListAnswer->m_iFilenameLen) + 4 - (size_t)bufptr % 4); + listAnswer->m_filenameLen = htonl(ntohl(listAnswer->m_filenameLen) + 4 - (size_t)bufptr % 4); memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data" bufptr += 4 - (size_t)bufptr % 4; } @@ -702,58 +702,58 @@ void ListBinCommand::Execute() DownloadQueue::Unlock(); - delete pRegEx; + delete regEx; - ListResponse.m_iNrTrailingNZBEntries = htonl(iNrNZBEntries); - ListResponse.m_iNrTrailingPPPEntries = htonl(iNrPPPEntries); - ListResponse.m_iNrTrailingFileEntries = htonl(iNrFileEntries); - ListResponse.m_iTrailingDataLength = htonl(bufsize); + ListResponse.m_nrTrailingNzbEntries = htonl(nrNzbEntries); + ListResponse.m_nrTrailingPPPEntries = htonl(nrPPPEntries); + ListResponse.m_nrTrailingFileEntries = htonl(nrFileEntries); + ListResponse.m_trailingDataLength = htonl(bufsize); } - if (htonl(ListRequest.m_bServerState)) + if (htonl(ListRequest.m_serverState)) { - DownloadQueue *pDownloadQueue = DownloadQueue::Lock(); - int iPostJobCount = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + DownloadQueue *downloadQueue = DownloadQueue::Lock(); + int postJobCount = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - iPostJobCount += pNZBInfo->GetPostInfo() ? 1 : 0; + NZBInfo* nzbInfo = *it; + postJobCount += nzbInfo->GetPostInfo() ? 1 : 0; } - long long lRemainingSize; - pDownloadQueue->CalcRemainingSize(&lRemainingSize, NULL); + long long remainingSize; + downloadQueue->CalcRemainingSize(&remainingSize, NULL); DownloadQueue::Unlock(); - unsigned long iSizeHi, iSizeLo; - ListResponse.m_iDownloadRate = htonl(g_pStatMeter->CalcCurrentDownloadSpeed()); - Util::SplitInt64(lRemainingSize, &iSizeHi, &iSizeLo); - ListResponse.m_iRemainingSizeHi = htonl(iSizeHi); - ListResponse.m_iRemainingSizeLo = htonl(iSizeLo); - ListResponse.m_iDownloadLimit = htonl(g_pOptions->GetDownloadRate()); - ListResponse.m_bDownloadPaused = htonl(g_pOptions->GetPauseDownload()); - ListResponse.m_bPostPaused = htonl(g_pOptions->GetPausePostProcess()); - ListResponse.m_bScanPaused = htonl(g_pOptions->GetPauseScan()); - ListResponse.m_iThreadCount = htonl(Thread::GetThreadCount() - 1); // not counting itself - ListResponse.m_iPostJobCount = htonl(iPostJobCount); + unsigned long sizeHi, sizeLo; + ListResponse.m_downloadRate = htonl(g_pStatMeter->CalcCurrentDownloadSpeed()); + Util::SplitInt64(remainingSize, &sizeHi, &sizeLo); + ListResponse.m_remainingSizeHi = htonl(sizeHi); + ListResponse.m_remainingSizeLo = htonl(sizeLo); + ListResponse.m_downloadLimit = htonl(g_pOptions->GetDownloadRate()); + ListResponse.m_downloadPaused = htonl(g_pOptions->GetPauseDownload()); + ListResponse.m_postPaused = htonl(g_pOptions->GetPausePostProcess()); + ListResponse.m_scanPaused = htonl(g_pOptions->GetPauseScan()); + ListResponse.m_threadCount = htonl(Thread::GetThreadCount() - 1); // not counting itself + ListResponse.m_postJobCount = htonl(postJobCount); - int iUpTimeSec, iDnTimeSec; - long long iAllBytes; - bool bStandBy; - g_pStatMeter->CalcTotalStat(&iUpTimeSec, &iDnTimeSec, &iAllBytes, &bStandBy); - ListResponse.m_iUpTimeSec = htonl(iUpTimeSec); - ListResponse.m_iDownloadTimeSec = htonl(iDnTimeSec); - ListResponse.m_bDownloadStandBy = htonl(bStandBy); - Util::SplitInt64(iAllBytes, &iSizeHi, &iSizeLo); - ListResponse.m_iDownloadedBytesHi = htonl(iSizeHi); - ListResponse.m_iDownloadedBytesLo = htonl(iSizeLo); + int upTimeSec, dnTimeSec; + long long allBytes; + bool standBy; + g_pStatMeter->CalcTotalStat(&upTimeSec, &dnTimeSec, &allBytes, &standBy); + ListResponse.m_upTimeSec = htonl(upTimeSec); + ListResponse.m_downloadTimeSec = htonl(dnTimeSec); + ListResponse.m_downloadStandBy = htonl(standBy); + Util::SplitInt64(allBytes, &sizeHi, &sizeLo); + ListResponse.m_downloadedBytesHi = htonl(sizeHi); + ListResponse.m_downloadedBytesLo = htonl(sizeLo); } // Send the request answer - m_pConnection->Send((char*) &ListResponse, sizeof(ListResponse)); + m_connection->Send((char*) &ListResponse, sizeof(ListResponse)); // Send the data if (bufsize > 0) { - m_pConnection->Send(buf, bufsize); + m_connection->Send(buf, bufsize); } free(buf); @@ -767,60 +767,60 @@ void LogBinCommand::Execute() return; } - MessageList* pMessages = g_pLog->LockMessages(); + MessageList* messages = g_pLog->LockMessages(); - int iNrEntries = ntohl(LogRequest.m_iLines); - unsigned int iIDFrom = ntohl(LogRequest.m_iIDFrom); - int iStart = pMessages->size(); - if (iNrEntries > 0) + int nrEntries = ntohl(LogRequest.m_lines); + unsigned int idFrom = ntohl(LogRequest.m_idFrom); + int start = messages->size(); + if (nrEntries > 0) { - if (iNrEntries > (int)pMessages->size()) + if (nrEntries > (int)messages->size()) { - iNrEntries = pMessages->size(); + nrEntries = messages->size(); } - iStart = pMessages->size() - iNrEntries; + start = messages->size() - nrEntries; } - if (iIDFrom > 0 && !pMessages->empty()) + if (idFrom > 0 && !messages->empty()) { - iStart = iIDFrom - pMessages->front()->GetID(); - if (iStart < 0) + start = idFrom - messages->front()->GetID(); + if (start < 0) { - iStart = 0; + start = 0; } - iNrEntries = pMessages->size() - iStart; - if (iNrEntries < 0) + nrEntries = messages->size() - start; + if (nrEntries < 0) { - iNrEntries = 0; + nrEntries = 0; } } // calculate required buffer size - int bufsize = iNrEntries * sizeof(SNZBLogResponseEntry); - for (unsigned int i = (unsigned int)iStart; i < pMessages->size(); i++) + int bufsize = nrEntries * sizeof(SNZBLogResponseEntry); + for (unsigned int i = (unsigned int)start; i < messages->size(); i++) { - Message* pMessage = (*pMessages)[i]; - bufsize += strlen(pMessage->GetText()) + 1; + Message* message = (*messages)[i]; + bufsize += strlen(message->GetText()) + 1; // align struct to 4-bytes, needed by ARM-processor (and may be others) bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0; } char* buf = (char*) malloc(bufsize); char* bufptr = buf; - for (unsigned int i = (unsigned int)iStart; i < pMessages->size(); i++) + for (unsigned int i = (unsigned int)start; i < messages->size(); i++) { - Message* pMessage = (*pMessages)[i]; - SNZBLogResponseEntry* pLogAnswer = (SNZBLogResponseEntry*) bufptr; - pLogAnswer->m_iID = htonl(pMessage->GetID()); - pLogAnswer->m_iKind = htonl(pMessage->GetKind()); - pLogAnswer->m_tTime = htonl((int)pMessage->GetTime()); - pLogAnswer->m_iTextLen = htonl(strlen(pMessage->GetText()) + 1); + Message* message = (*messages)[i]; + SNZBLogResponseEntry* logAnswer = (SNZBLogResponseEntry*) bufptr; + logAnswer->m_id = htonl(message->GetID()); + logAnswer->m_kind = htonl(message->GetKind()); + logAnswer->m_time = htonl((int)message->GetTime()); + logAnswer->m_textLen = htonl(strlen(message->GetText()) + 1); bufptr += sizeof(SNZBLogResponseEntry); - strcpy(bufptr, pMessage->GetText()); - bufptr += ntohl(pLogAnswer->m_iTextLen); + strcpy(bufptr, message->GetText()); + bufptr += ntohl(logAnswer->m_textLen); // align struct to 4-bytes, needed by ARM-processor (and may be others) if ((size_t)bufptr % 4 > 0) { - pLogAnswer->m_iTextLen = htonl(ntohl(pLogAnswer->m_iTextLen) + 4 - (size_t)bufptr % 4); + logAnswer->m_textLen = htonl(ntohl(logAnswer->m_textLen) + 4 - (size_t)bufptr % 4); memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data" bufptr += 4 - (size_t)bufptr % 4; } @@ -829,19 +829,19 @@ void LogBinCommand::Execute() g_pLog->UnlockMessages(); SNZBLogResponse LogResponse; - LogResponse.m_MessageBase.m_iSignature = htonl(NZBMESSAGE_SIGNATURE); - LogResponse.m_MessageBase.m_iStructSize = htonl(sizeof(LogResponse)); - LogResponse.m_iEntrySize = htonl(sizeof(SNZBLogResponseEntry)); - LogResponse.m_iNrTrailingEntries = htonl(iNrEntries); - LogResponse.m_iTrailingDataLength = htonl(bufsize); + LogResponse.m_messageBase.m_signature = htonl(NZBMESSAGE_SIGNATURE); + LogResponse.m_messageBase.m_structSize = htonl(sizeof(LogResponse)); + LogResponse.m_entrySize = htonl(sizeof(SNZBLogResponseEntry)); + LogResponse.m_nrTrailingEntries = htonl(nrEntries); + LogResponse.m_trailingDataLength = htonl(bufsize); // Send the request answer - m_pConnection->Send((char*) &LogResponse, sizeof(LogResponse)); + m_connection->Send((char*) &LogResponse, sizeof(LogResponse)); // Send the data if (bufsize > 0) { - m_pConnection->Send(buf, bufsize); + m_connection->Send(buf, bufsize); } free(buf); @@ -855,79 +855,79 @@ void EditQueueBinCommand::Execute() return; } - int iNrIDEntries = ntohl(EditQueueRequest.m_iNrTrailingIDEntries); - int iNrNameEntries = ntohl(EditQueueRequest.m_iNrTrailingNameEntries); - int iNameEntriesLen = ntohl(EditQueueRequest.m_iTrailingNameEntriesLen); - int iAction = ntohl(EditQueueRequest.m_iAction); - int iMatchMode = ntohl(EditQueueRequest.m_iMatchMode); - int iOffset = ntohl(EditQueueRequest.m_iOffset); - int iTextLen = ntohl(EditQueueRequest.m_iTextLen); - unsigned int iBufLength = ntohl(EditQueueRequest.m_iTrailingDataLength); + int nrIdEntries = ntohl(EditQueueRequest.m_nrTrailingIdEntries); + int nrNameEntries = ntohl(EditQueueRequest.m_nrTrailingNameEntries); + int nameEntriesLen = ntohl(EditQueueRequest.m_trailingNameEntriesLen); + int action = ntohl(EditQueueRequest.m_action); + int matchMode = ntohl(EditQueueRequest.m_matchMode); + int offset = ntohl(EditQueueRequest.m_offset); + int textLen = ntohl(EditQueueRequest.m_textLen); + unsigned int bufLength = ntohl(EditQueueRequest.m_trailingDataLength); - if (iNrIDEntries * sizeof(int32_t) + iTextLen + iNameEntriesLen != iBufLength) + if (nrIdEntries * sizeof(int32_t) + textLen + nameEntriesLen != bufLength) { error("Invalid struct size"); return; } - char* pBuf = (char*)malloc(iBufLength); + char* buf = (char*)malloc(bufLength); - if (!m_pConnection->Recv(pBuf, iBufLength)) + if (!m_connection->Recv(buf, bufLength)) { error("invalid request"); - free(pBuf); + free(buf); return; } - if (iNrIDEntries <= 0 && iNrNameEntries <= 0) + if (nrIdEntries <= 0 && nrNameEntries <= 0) { SendBoolResponse(false, "Edit-Command failed: no IDs/Names specified"); return; } - char* szText = iTextLen > 0 ? pBuf : NULL; - int32_t* pIDs = (int32_t*)(pBuf + iTextLen); - char* pNames = (pBuf + iTextLen + iNrIDEntries * sizeof(int32_t)); + char* text = textLen > 0 ? buf : NULL; + int32_t* ids = (int32_t*)(buf + textLen); + char* names = (buf + textLen + nrIdEntries * sizeof(int32_t)); IDList cIDList; NameList cNameList; - if (iNrIDEntries > 0) + if (nrIdEntries > 0) { - cIDList.reserve(iNrIDEntries); - for (int i = 0; i < iNrIDEntries; i++) + cIDList.reserve(nrIdEntries); + for (int i = 0; i < nrIdEntries; i++) { - cIDList.push_back(ntohl(pIDs[i])); + cIDList.push_back(ntohl(ids[i])); } } - if (iNrNameEntries > 0) + if (nrNameEntries > 0) { - cNameList.reserve(iNrNameEntries); - for (int i = 0; i < iNrNameEntries; i++) + cNameList.reserve(nrNameEntries); + for (int i = 0; i < nrNameEntries; i++) { - cNameList.push_back(pNames); - pNames += strlen(pNames) + 1; + cNameList.push_back(names); + names += strlen(names) + 1; } } - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - bool bOK = pDownloadQueue->EditList( - iNrIDEntries > 0 ? &cIDList : NULL, - iNrNameEntries > 0 ? &cNameList : NULL, - (DownloadQueue::EMatchMode)iMatchMode, (DownloadQueue::EEditAction)iAction, iOffset, szText); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + bool ok = downloadQueue->EditList( + nrIdEntries > 0 ? &cIDList : NULL, + nrNameEntries > 0 ? &cNameList : NULL, + (DownloadQueue::EMatchMode)matchMode, (DownloadQueue::EEditAction)action, offset, text); DownloadQueue::Unlock(); - free(pBuf); + free(buf); - if (bOK) + if (ok) { SendBoolResponse(true, "Edit-Command completed successfully"); } else { #ifndef HAVE_REGEX_H - if ((QueueEditor::EMatchMode)iMatchMode == QueueEditor::mmRegEx) + if ((QueueEditor::EMatchMode)matchMode == QueueEditor::mmRegEx) { SendBoolResponse(false, "Edit-Command failed: the program was compiled without RegEx-support"); return; @@ -947,74 +947,74 @@ void PostQueueBinCommand::Execute() SNZBPostQueueResponse PostQueueResponse; memset(&PostQueueResponse, 0, sizeof(PostQueueResponse)); - PostQueueResponse.m_MessageBase.m_iSignature = htonl(NZBMESSAGE_SIGNATURE); - PostQueueResponse.m_MessageBase.m_iStructSize = htonl(sizeof(PostQueueResponse)); - PostQueueResponse.m_iEntrySize = htonl(sizeof(SNZBPostQueueResponseEntry)); + PostQueueResponse.m_messageBase.m_signature = htonl(NZBMESSAGE_SIGNATURE); + PostQueueResponse.m_messageBase.m_structSize = htonl(sizeof(PostQueueResponse)); + PostQueueResponse.m_entrySize = htonl(sizeof(SNZBPostQueueResponseEntry)); char* buf = NULL; int bufsize = 0; // Make a data structure and copy all the elements of the list into it - NZBList* pNZBList = DownloadQueue::Lock()->GetQueue(); + NZBList* nzbList = DownloadQueue::Lock()->GetQueue(); // calculate required buffer size int NrEntries = 0; - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo = *it; - PostInfo* pPostInfo = pNZBInfo->GetPostInfo(); - if (!pPostInfo) + NZBInfo* nzbInfo = *it; + PostInfo* postInfo = nzbInfo->GetPostInfo(); + if (!postInfo) { continue; } NrEntries++; bufsize += sizeof(SNZBPostQueueResponseEntry); - bufsize += strlen(pPostInfo->GetNZBInfo()->GetFilename()) + 1; - bufsize += strlen(pPostInfo->GetNZBInfo()->GetName()) + 1; - bufsize += strlen(pPostInfo->GetNZBInfo()->GetDestDir()) + 1; - bufsize += strlen(pPostInfo->GetProgressLabel()) + 1; + bufsize += strlen(postInfo->GetNZBInfo()->GetFilename()) + 1; + bufsize += strlen(postInfo->GetNZBInfo()->GetName()) + 1; + bufsize += strlen(postInfo->GetNZBInfo()->GetDestDir()) + 1; + bufsize += strlen(postInfo->GetProgressLabel()) + 1; // align struct to 4-bytes, needed by ARM-processor (and may be others) bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0; } - time_t tCurTime = time(NULL); + time_t curTime = time(NULL); buf = (char*) malloc(bufsize); char* bufptr = buf; - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo = *it; - PostInfo* pPostInfo = pNZBInfo->GetPostInfo(); - if (!pPostInfo) + NZBInfo* nzbInfo = *it; + PostInfo* postInfo = nzbInfo->GetPostInfo(); + if (!postInfo) { continue; } - SNZBPostQueueResponseEntry* pPostQueueAnswer = (SNZBPostQueueResponseEntry*) bufptr; - pPostQueueAnswer->m_iID = htonl(pNZBInfo->GetID()); - pPostQueueAnswer->m_iStage = htonl(pPostInfo->GetStage()); - pPostQueueAnswer->m_iStageProgress = htonl(pPostInfo->GetStageProgress()); - pPostQueueAnswer->m_iFileProgress = htonl(pPostInfo->GetFileProgress()); - pPostQueueAnswer->m_iTotalTimeSec = htonl((int)(pPostInfo->GetStartTime() ? tCurTime - pPostInfo->GetStartTime() : 0)); - pPostQueueAnswer->m_iStageTimeSec = htonl((int)(pPostInfo->GetStageTime() ? tCurTime - pPostInfo->GetStageTime() : 0)); - pPostQueueAnswer->m_iNZBFilenameLen = htonl(strlen(pPostInfo->GetNZBInfo()->GetFilename()) + 1); - pPostQueueAnswer->m_iInfoNameLen = htonl(strlen(pPostInfo->GetNZBInfo()->GetName()) + 1); - pPostQueueAnswer->m_iDestDirLen = htonl(strlen(pPostInfo->GetNZBInfo()->GetDestDir()) + 1); - pPostQueueAnswer->m_iProgressLabelLen = htonl(strlen(pPostInfo->GetProgressLabel()) + 1); + SNZBPostQueueResponseEntry* postQueueAnswer = (SNZBPostQueueResponseEntry*) bufptr; + postQueueAnswer->m_id = htonl(nzbInfo->GetID()); + postQueueAnswer->m_stage = htonl(postInfo->GetStage()); + postQueueAnswer->m_stageProgress = htonl(postInfo->GetStageProgress()); + postQueueAnswer->m_fileProgress = htonl(postInfo->GetFileProgress()); + postQueueAnswer->m_totalTimeSec = htonl((int)(postInfo->GetStartTime() ? curTime - postInfo->GetStartTime() : 0)); + postQueueAnswer->m_stageTimeSec = htonl((int)(postInfo->GetStageTime() ? curTime - postInfo->GetStageTime() : 0)); + postQueueAnswer->m_nzbFilenameLen = htonl(strlen(postInfo->GetNZBInfo()->GetFilename()) + 1); + postQueueAnswer->m_infoNameLen = htonl(strlen(postInfo->GetNZBInfo()->GetName()) + 1); + postQueueAnswer->m_destDirLen = htonl(strlen(postInfo->GetNZBInfo()->GetDestDir()) + 1); + postQueueAnswer->m_progressLabelLen = htonl(strlen(postInfo->GetProgressLabel()) + 1); bufptr += sizeof(SNZBPostQueueResponseEntry); - strcpy(bufptr, pPostInfo->GetNZBInfo()->GetFilename()); - bufptr += ntohl(pPostQueueAnswer->m_iNZBFilenameLen); - strcpy(bufptr, pPostInfo->GetNZBInfo()->GetName()); - bufptr += ntohl(pPostQueueAnswer->m_iInfoNameLen); - strcpy(bufptr, pPostInfo->GetNZBInfo()->GetDestDir()); - bufptr += ntohl(pPostQueueAnswer->m_iDestDirLen); - strcpy(bufptr, pPostInfo->GetProgressLabel()); - bufptr += ntohl(pPostQueueAnswer->m_iProgressLabelLen); + strcpy(bufptr, postInfo->GetNZBInfo()->GetFilename()); + bufptr += ntohl(postQueueAnswer->m_nzbFilenameLen); + strcpy(bufptr, postInfo->GetNZBInfo()->GetName()); + bufptr += ntohl(postQueueAnswer->m_infoNameLen); + strcpy(bufptr, postInfo->GetNZBInfo()->GetDestDir()); + bufptr += ntohl(postQueueAnswer->m_destDirLen); + strcpy(bufptr, postInfo->GetProgressLabel()); + bufptr += ntohl(postQueueAnswer->m_progressLabelLen); // align struct to 4-bytes, needed by ARM-processor (and may be others) if ((size_t)bufptr % 4 > 0) { - pPostQueueAnswer->m_iProgressLabelLen = htonl(ntohl(pPostQueueAnswer->m_iProgressLabelLen) + 4 - (size_t)bufptr % 4); + postQueueAnswer->m_progressLabelLen = htonl(ntohl(postQueueAnswer->m_progressLabelLen) + 4 - (size_t)bufptr % 4); memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data" bufptr += 4 - (size_t)bufptr % 4; } @@ -1022,16 +1022,16 @@ void PostQueueBinCommand::Execute() DownloadQueue::Unlock(); - PostQueueResponse.m_iNrTrailingEntries = htonl(NrEntries); - PostQueueResponse.m_iTrailingDataLength = htonl(bufsize); + PostQueueResponse.m_nrTrailingEntries = htonl(NrEntries); + PostQueueResponse.m_trailingDataLength = htonl(bufsize); // Send the request answer - m_pConnection->Send((char*) &PostQueueResponse, sizeof(PostQueueResponse)); + m_connection->Send((char*) &PostQueueResponse, sizeof(PostQueueResponse)); // Send the data if (bufsize > 0) { - m_pConnection->Send(buf, bufsize); + m_connection->Send(buf, bufsize); } free(buf); @@ -1045,39 +1045,39 @@ void WriteLogBinCommand::Execute() return; } - char* pRecvBuffer = (char*)malloc(ntohl(WriteLogRequest.m_iTrailingDataLength) + 1); + char* recvBuffer = (char*)malloc(ntohl(WriteLogRequest.m_trailingDataLength) + 1); - if (!m_pConnection->Recv(pRecvBuffer, ntohl(WriteLogRequest.m_iTrailingDataLength))) + if (!m_connection->Recv(recvBuffer, ntohl(WriteLogRequest.m_trailingDataLength))) { error("invalid request"); - free(pRecvBuffer); + free(recvBuffer); return; } bool OK = true; - switch ((Message::EKind)ntohl(WriteLogRequest.m_iKind)) + switch ((Message::EKind)ntohl(WriteLogRequest.m_kind)) { case Message::mkDetail: - detail(pRecvBuffer); + detail(recvBuffer); break; case Message::mkInfo: - info(pRecvBuffer); + info(recvBuffer); break; case Message::mkWarning: - warn(pRecvBuffer); + warn(recvBuffer); break; case Message::mkError: - error(pRecvBuffer); + error(recvBuffer); break; case Message::mkDebug: - debug(pRecvBuffer); + debug(recvBuffer); break; default: OK = false; } SendBoolResponse(OK, OK ? "Message added to log" : "Invalid message-kind"); - free(pRecvBuffer); + free(recvBuffer); } void ScanBinCommand::Execute() @@ -1088,10 +1088,10 @@ void ScanBinCommand::Execute() return; } - bool bSyncMode = ntohl(ScanRequest.m_bSyncMode); + bool syncMode = ntohl(ScanRequest.m_syncMode); - g_pScanner->ScanNZBDir(bSyncMode); - SendBoolResponse(true, bSyncMode ? "Scan-Command completed" : "Scan-Command scheduled successfully"); + g_pScanner->ScanNZBDir(syncMode); + SendBoolResponse(true, syncMode ? "Scan-Command completed" : "Scan-Command scheduled successfully"); } void HistoryBinCommand::Execute() @@ -1102,39 +1102,39 @@ void HistoryBinCommand::Execute() return; } - bool bShowHidden = ntohl(HistoryRequest.m_bHidden); + bool showHidden = ntohl(HistoryRequest.m_hidden); SNZBHistoryResponse HistoryResponse; memset(&HistoryResponse, 0, sizeof(HistoryResponse)); - HistoryResponse.m_MessageBase.m_iSignature = htonl(NZBMESSAGE_SIGNATURE); - HistoryResponse.m_MessageBase.m_iStructSize = htonl(sizeof(HistoryResponse)); - HistoryResponse.m_iEntrySize = htonl(sizeof(SNZBHistoryResponseEntry)); + HistoryResponse.m_messageBase.m_signature = htonl(NZBMESSAGE_SIGNATURE); + HistoryResponse.m_messageBase.m_structSize = htonl(sizeof(HistoryResponse)); + HistoryResponse.m_entrySize = htonl(sizeof(SNZBHistoryResponseEntry)); char* buf = NULL; int bufsize = 0; // Make a data structure and copy all the elements of the list into it - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); // calculate required buffer size for nzbs - int iNrEntries = 0; - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + int nrEntries = 0; + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() != HistoryInfo::hkDup || bShowHidden) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() != HistoryInfo::hkDup || showHidden) { - iNrEntries++; + nrEntries++; } } - bufsize += iNrEntries * sizeof(SNZBHistoryResponseEntry); - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + bufsize += nrEntries * sizeof(SNZBHistoryResponseEntry); + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() != HistoryInfo::hkDup || bShowHidden) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() != HistoryInfo::hkDup || showHidden) { - char szNicename[1024]; - pHistoryInfo->GetName(szNicename, sizeof(szNicename)); - bufsize += strlen(szNicename) + 1; + char nicename[1024]; + historyInfo->GetName(nicename, sizeof(nicename)); + bufsize += strlen(nicename) + 1; // align struct to 4-bytes, needed by ARM-processor (and may be others) bufsize += bufsize % 4 > 0 ? 4 - bufsize % 4 : 0; } @@ -1144,52 +1144,52 @@ void HistoryBinCommand::Execute() char* bufptr = buf; // write nzb entries - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; - if (pHistoryInfo->GetKind() != HistoryInfo::hkDup || bShowHidden) + HistoryInfo* historyInfo = *it; + if (historyInfo->GetKind() != HistoryInfo::hkDup || showHidden) { - SNZBHistoryResponseEntry* pListAnswer = (SNZBHistoryResponseEntry*) bufptr; - pListAnswer->m_iID = htonl(pHistoryInfo->GetID()); - pListAnswer->m_iKind = htonl((int)pHistoryInfo->GetKind()); - pListAnswer->m_tTime = htonl((int)pHistoryInfo->GetTime()); + SNZBHistoryResponseEntry* listAnswer = (SNZBHistoryResponseEntry*) bufptr; + listAnswer->m_id = htonl(historyInfo->GetID()); + listAnswer->m_kind = htonl((int)historyInfo->GetKind()); + listAnswer->m_time = htonl((int)historyInfo->GetTime()); - char szNicename[1024]; - pHistoryInfo->GetName(szNicename, sizeof(szNicename)); - pListAnswer->m_iNicenameLen = htonl(strlen(szNicename) + 1); + char nicename[1024]; + historyInfo->GetName(nicename, sizeof(nicename)); + listAnswer->m_nicenameLen = htonl(strlen(nicename) + 1); - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb) + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { - NZBInfo* pNZBInfo = pHistoryInfo->GetNZBInfo(); - unsigned long iSizeHi, iSizeLo; - Util::SplitInt64(pNZBInfo->GetSize(), &iSizeHi, &iSizeLo); - pListAnswer->m_iSizeLo = htonl(iSizeLo); - pListAnswer->m_iSizeHi = htonl(iSizeHi); - pListAnswer->m_iFileCount = htonl(pNZBInfo->GetFileCount()); - pListAnswer->m_iParStatus = htonl(pNZBInfo->GetParStatus()); - pListAnswer->m_iScriptStatus = htonl(pNZBInfo->GetScriptStatuses()->CalcTotalStatus()); + NZBInfo* nzbInfo = historyInfo->GetNZBInfo(); + unsigned long sizeHi, sizeLo; + Util::SplitInt64(nzbInfo->GetSize(), &sizeHi, &sizeLo); + listAnswer->m_sizeLo = htonl(sizeLo); + listAnswer->m_sizeHi = htonl(sizeHi); + listAnswer->m_fileCount = htonl(nzbInfo->GetFileCount()); + listAnswer->m_parStatus = htonl(nzbInfo->GetParStatus()); + listAnswer->m_scriptStatus = htonl(nzbInfo->GetScriptStatuses()->CalcTotalStatus()); } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkDup && bShowHidden) + else if (historyInfo->GetKind() == HistoryInfo::hkDup && showHidden) { - DupInfo* pDupInfo = pHistoryInfo->GetDupInfo(); - unsigned long iSizeHi, iSizeLo; - Util::SplitInt64(pDupInfo->GetSize(), &iSizeHi, &iSizeLo); - pListAnswer->m_iSizeLo = htonl(iSizeLo); - pListAnswer->m_iSizeHi = htonl(iSizeHi); + DupInfo* dupInfo = historyInfo->GetDupInfo(); + unsigned long sizeHi, sizeLo; + Util::SplitInt64(dupInfo->GetSize(), &sizeHi, &sizeLo); + listAnswer->m_sizeLo = htonl(sizeLo); + listAnswer->m_sizeHi = htonl(sizeHi); } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + else if (historyInfo->GetKind() == HistoryInfo::hkUrl) { - NZBInfo* pNZBInfo = pHistoryInfo->GetNZBInfo(); - pListAnswer->m_iUrlStatus = htonl(pNZBInfo->GetUrlStatus()); + NZBInfo* nzbInfo = historyInfo->GetNZBInfo(); + listAnswer->m_urlStatus = htonl(nzbInfo->GetUrlStatus()); } bufptr += sizeof(SNZBHistoryResponseEntry); - strcpy(bufptr, szNicename); - bufptr += ntohl(pListAnswer->m_iNicenameLen); + strcpy(bufptr, nicename); + bufptr += ntohl(listAnswer->m_nicenameLen); // align struct to 4-bytes, needed by ARM-processor (and may be others) if ((size_t)bufptr % 4 > 0) { - pListAnswer->m_iNicenameLen = htonl(ntohl(pListAnswer->m_iNicenameLen) + 4 - (size_t)bufptr % 4); + listAnswer->m_nicenameLen = htonl(ntohl(listAnswer->m_nicenameLen) + 4 - (size_t)bufptr % 4); memset(bufptr, 0, 4 - (size_t)bufptr % 4); //suppress valgrind warning "uninitialized data" bufptr += 4 - (size_t)bufptr % 4; } @@ -1198,16 +1198,16 @@ void HistoryBinCommand::Execute() DownloadQueue::Unlock(); - HistoryResponse.m_iNrTrailingEntries = htonl(iNrEntries); - HistoryResponse.m_iTrailingDataLength = htonl(bufsize); + HistoryResponse.m_nrTrailingEntries = htonl(nrEntries); + HistoryResponse.m_trailingDataLength = htonl(bufsize); // Send the request answer - m_pConnection->Send((char*) &HistoryResponse, sizeof(HistoryResponse)); + m_connection->Send((char*) &HistoryResponse, sizeof(HistoryResponse)); // Send the data if (bufsize > 0) { - m_pConnection->Send(buf, bufsize); + m_connection->Send(buf, bufsize); } free(buf); diff --git a/daemon/remote/BinRpc.h b/daemon/remote/BinRpc.h index e29b4bbf..c78e226e 100644 --- a/daemon/remote/BinRpc.h +++ b/daemon/remote/BinRpc.h @@ -33,15 +33,15 @@ class BinRpcProcessor { private: - SNZBRequestBase m_MessageBase; - Connection* m_pConnection; + SNZBRequestBase m_messageBase; + Connection* m_connection; void Dispatch(); public: BinRpcProcessor(); void Execute(); - void SetConnection(Connection* pConnection) { m_pConnection = pConnection; } + void SetConnection(Connection* connection) { m_connection = connection; } }; #endif diff --git a/daemon/remote/MessageBase.h b/daemon/remote/MessageBase.h index 66f819f7..b3bbf9c9 100644 --- a/daemon/remote/MessageBase.h +++ b/daemon/remote/MessageBase.h @@ -50,118 +50,118 @@ static const int NZBREQUESTPASSWORDSIZE = 32; */ // Possible values for field "m_iType" of struct "SNZBRequestBase": -enum eRemoteRequest +enum remoteRequest { - eRemoteRequestDownload = 1, - eRemoteRequestPauseUnpause, - eRemoteRequestList, - eRemoteRequestSetDownloadRate, - eRemoteRequestDumpDebug, - eRemoteRequestEditQueue, - eRemoteRequestLog, - eRemoteRequestShutdown, - eRemoteRequestReload, - eRemoteRequestVersion, - eRemoteRequestPostQueue, - eRemoteRequestWriteLog, - eRemoteRequestScan, - eRemoteRequestHistory + remoteRequestDownload = 1, + remoteRequestPauseUnpause, + remoteRequestList, + remoteRequestSetDownloadRate, + remoteRequestDumpDebug, + remoteRequestEditQueue, + remoteRequestLog, + remoteRequestShutdown, + remoteRequestReload, + remoteRequestVersion, + remoteRequestPostQueue, + remoteRequestWriteLog, + remoteRequestScan, + remoteRequestHistory }; // Possible values for field "m_iAction" of struct "SNZBPauseUnpauseRequest": -enum eRemotePauseUnpauseAction +enum remotePauseUnpauseAction { - eRemotePauseUnpauseActionDownload = 1, // pause/unpause download queue - eRemotePauseUnpauseActionPostProcess, // pause/unpause post-processor queue - eRemotePauseUnpauseActionScan // pause/unpause scan of incoming nzb-directory + remotePauseUnpauseActionDownload = 1, // pause/unpause download queue + remotePauseUnpauseActionPostProcess, // pause/unpause post-processor queue + remotePauseUnpauseActionScan // pause/unpause scan of incoming nzb-directory }; // Possible values for field "m_iMatchMode" of struct "SNZBEditQueueRequest": -enum eRemoteMatchMode +enum remoteMatchMode { - eRemoteMatchModeID = 1, // ID - eRemoteMatchModeName, // Name - eRemoteMatchModeRegEx, // RegEx + remoteMatchModeId = 1, // ID + remoteMatchModeName, // Name + remoteMatchModeRegEx, // RegEx }; // The basic SNZBRequestBase struct, used in all requests struct SNZBRequestBase { - int32_t m_iSignature; // Signature must be NZBMESSAGE_SIGNATURE in integer-value - int32_t m_iStructSize; // Size of the entire struct - int32_t m_iType; // Message type, see enum in NZBMessageRequest-namespace - char m_szUsername[NZBREQUESTPASSWORDSIZE]; // User name - char m_szPassword[NZBREQUESTPASSWORDSIZE]; // Password + int32_t m_signature; // Signature must be NZBMESSAGE_SIGNATURE in integer-value + int32_t m_structSize; // Size of the entire struct + int32_t m_type; // Message type, see enum in NZBMessageRequest-namespace + char m_username[NZBREQUESTPASSWORDSIZE]; // User name + char m_password[NZBREQUESTPASSWORDSIZE]; // Password }; // The basic SNZBResposneBase struct, used in all responses struct SNZBResponseBase { - int32_t m_iSignature; // Signature must be NZBMESSAGE_SIGNATURE in integer-value - int32_t m_iStructSize; // Size of the entire struct + int32_t m_signature; // Signature must be NZBMESSAGE_SIGNATURE in integer-value + int32_t m_structSize; // Size of the entire struct }; // A download request struct SNZBDownloadRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - char m_szNZBFilename[NZBREQUESTFILENAMESIZE];// Name of nzb-file. For URLs can be empty, then the filename is read from URL download response - char m_szCategory[NZBREQUESTFILENAMESIZE]; // Category, can be empty - int32_t m_bAddFirst; // 1 - add file to the top of download queue - int32_t m_bAddPaused; // 1 - pause added files - int32_t m_iPriority; // Priority for files (0 - default) - int32_t m_iDupeScore; // Duplicate score - int32_t m_iDupeMode; // Duplicate mode (EDupeMode) - char m_szDupeKey[NZBREQUESTFILENAMESIZE]; // Duplicate key - int32_t m_iTrailingDataLength; // Length of nzb-file in bytes + SNZBRequestBase m_messageBase; // Must be the first in the struct + char m_nzbFilename[NZBREQUESTFILENAMESIZE];// Name of nzb-file. For URLs can be empty, then the filename is read from URL download response + char m_category[NZBREQUESTFILENAMESIZE]; // Category, can be empty + int32_t m_addFirst; // 1 - add file to the top of download queue + int32_t m_addPaused; // 1 - pause added files + int32_t m_priority; // Priority for files (0 - default) + int32_t m_dupeScore; // Duplicate score + int32_t m_dupeMode; // Duplicate mode (EDupeMode) + char m_dupeKey[NZBREQUESTFILENAMESIZE]; // Duplicate key + int32_t m_trailingDataLength; // Length of nzb-file in bytes //char m_szContent[m_iTrailingDataLength]; // variable sized }; // A download response struct SNZBDownloadResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // A list and status request struct SNZBListRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_bFileList; // 1 - return file list - int32_t m_bServerState; // 1 - return server state - int32_t m_iMatchMode; // File/Group match mode, see enum eRemoteMatchMode (only values eRemoteMatchModeID (no filter) and eRemoteMatchModeRegEx are allowed) - int32_t m_bMatchGroup; // 0 - match files; 1 - match nzbs (when m_iMatchMode == eRemoteMatchModeRegEx) - char m_szPattern[NZBREQUESTFILENAMESIZE]; // RegEx Pattern (when m_iMatchMode == eRemoteMatchModeRegEx) + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_fileList; // 1 - return file list + int32_t m_serverState; // 1 - return server state + int32_t m_matchMode; // File/Group match mode, see enum eRemoteMatchMode (only values eRemoteMatchModeID (no filter) and eRemoteMatchModeRegEx are allowed) + int32_t m_matchGroup; // 0 - match files; 1 - match nzbs (when m_iMatchMode == eRemoteMatchModeRegEx) + char m_pattern[NZBREQUESTFILENAMESIZE]; // RegEx Pattern (when m_iMatchMode == eRemoteMatchModeRegEx) }; // A list response struct SNZBListResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_iEntrySize; // Size of the SNZBListResponseEntry-struct - int32_t m_iRemainingSizeLo; // Remaining size in bytes, Low 32-bits of 64-bit value - int32_t m_iRemainingSizeHi; // Remaining size in bytes, High 32-bits of 64-bit value - int32_t m_iDownloadRate; // Current download speed, in Bytes pro Second - int32_t m_iDownloadLimit; // Current download limit, in Bytes pro Second - int32_t m_bDownloadPaused; // 1 - download queue is currently in paused-state - int32_t m_bDownload2Paused; // 1 - download queue is currently in paused-state (second pause-register) - int32_t m_bDownloadStandBy; // 0 - there are currently downloads running, 1 - no downloads in progress (download queue paused or all download jobs completed) - int32_t m_bPostPaused; // 1 - post-processor queue is currently in paused-state - int32_t m_bScanPaused; // 1 - scaning of incoming directory is currently in paused-state - int32_t m_iThreadCount; // Number of threads running - int32_t m_iPostJobCount; // Number of jobs in post-processor queue (including current job) - int32_t m_iUpTimeSec; // Server up time in seconds - int32_t m_iDownloadTimeSec; // Server download time in seconds (up_time - standby_time) - int32_t m_iDownloadedBytesLo; // Amount of data downloaded since server start, Low 32-bits of 64-bit value - int32_t m_iDownloadedBytesHi; // Amount of data downloaded since server start, High 32-bits of 64-bit value - int32_t m_bRegExValid; // 0 - error in RegEx-pattern, 1 - RegEx-pattern is valid (only when Request has eRemoteMatchModeRegEx) - int32_t m_iNrTrailingNZBEntries; // Number of List-NZB-entries, following to this structure - int32_t m_iNrTrailingPPPEntries; // Number of List-PPP-entries, following to this structure - int32_t m_iNrTrailingFileEntries; // Number of List-File-entries, following to this structure - int32_t m_iTrailingDataLength; // Length of all List-entries, following to this structure + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_entrySize; // Size of the SNZBListResponseEntry-struct + int32_t m_remainingSizeLo; // Remaining size in bytes, Low 32-bits of 64-bit value + int32_t m_remainingSizeHi; // Remaining size in bytes, High 32-bits of 64-bit value + int32_t m_downloadRate; // Current download speed, in Bytes pro Second + int32_t m_downloadLimit; // Current download limit, in Bytes pro Second + int32_t m_downloadPaused; // 1 - download queue is currently in paused-state + int32_t m_download2Paused; // 1 - download queue is currently in paused-state (second pause-register) + int32_t m_downloadStandBy; // 0 - there are currently downloads running, 1 - no downloads in progress (download queue paused or all download jobs completed) + int32_t m_postPaused; // 1 - post-processor queue is currently in paused-state + int32_t m_scanPaused; // 1 - scaning of incoming directory is currently in paused-state + int32_t m_threadCount; // Number of threads running + int32_t m_postJobCount; // Number of jobs in post-processor queue (including current job) + int32_t m_upTimeSec; // Server up time in seconds + int32_t m_downloadTimeSec; // Server download time in seconds (up_time - standby_time) + int32_t m_downloadedBytesLo; // Amount of data downloaded since server start, Low 32-bits of 64-bit value + int32_t m_downloadedBytesHi; // Amount of data downloaded since server start, High 32-bits of 64-bit value + int32_t m_regExValid; // 0 - error in RegEx-pattern, 1 - RegEx-pattern is valid (only when Request has eRemoteMatchModeRegEx) + int32_t m_nrTrailingNzbEntries; // Number of List-NZB-entries, following to this structure + int32_t m_nrTrailingPPPEntries; // Number of List-PPP-entries, following to this structure + int32_t m_nrTrailingFileEntries; // Number of List-File-entries, following to this structure + int32_t m_trailingDataLength; // Length of all List-entries, following to this structure // SNZBListResponseEntry m_NZBEntries[m_iNrTrailingNZBEntries] // variable sized // SNZBListResponseEntry m_PPPEntries[m_iNrTrailingPPPEntries] // variable sized // SNZBListResponseEntry m_FileEntries[m_iNrTrailingFileEntries] // variable sized @@ -170,23 +170,23 @@ struct SNZBListResponse // A list response nzb entry struct SNZBListResponseNZBEntry { - int32_t m_iID; // NZB-ID - int32_t m_iKind; // Item Kind (see NZBInfo::Kind) - int32_t m_iSizeLo; // Size of all files in bytes, Low 32-bits of 64-bit value - int32_t m_iSizeHi; // Size of all files in bytes, High 32-bits of 64-bit value - int32_t m_iRemainingSizeLo; // Size of remaining (unpaused) files in bytes, Low 32-bits of 64-bit value - int32_t m_iRemainingSizeHi; // Size of remaining (unpaused) files in bytes, High 32-bits of 64-bit value - int32_t m_iPausedSizeLo; // Size of npaused files in bytes, Low 32-bits of 64-bit value - int32_t m_iPausedSizeHi; // Size of paused files in bytes, High 32-bits of 64-bit value - int32_t m_iPausedCount; // Number of paused files - int32_t m_iRemainingParCount; // Number of remaining par-files - int32_t m_iPriority; // Download priority - int32_t m_bMatch; // 1 - group matches the pattern (only when Request has eRemoteMatchModeRegEx) - int32_t m_iFilenameLen; // Length of Filename-string (m_szFilename), following to this record - int32_t m_iNameLen; // Length of Name-string (m_szName), following to this record - int32_t m_iDestDirLen; // Length of DestDir-string (m_szDestDir), following to this record - int32_t m_iCategoryLen; // Length of Category-string (m_szCategory), following to this record - int32_t m_iQueuedFilenameLen; // Length of queued file name (m_szQueuedFilename), following to this record + int32_t m_id; // NZB-ID + int32_t m_kind; // Item Kind (see NZBInfo::Kind) + int32_t m_sizeLo; // Size of all files in bytes, Low 32-bits of 64-bit value + int32_t m_sizeHi; // Size of all files in bytes, High 32-bits of 64-bit value + int32_t m_remainingSizeLo; // Size of remaining (unpaused) files in bytes, Low 32-bits of 64-bit value + int32_t m_remainingSizeHi; // Size of remaining (unpaused) files in bytes, High 32-bits of 64-bit value + int32_t m_pausedSizeLo; // Size of npaused files in bytes, Low 32-bits of 64-bit value + int32_t m_pausedSizeHi; // Size of paused files in bytes, High 32-bits of 64-bit value + int32_t m_pausedCount; // Number of paused files + int32_t m_remainingParCount; // Number of remaining par-files + int32_t m_priority; // Download priority + int32_t m_match; // 1 - group matches the pattern (only when Request has eRemoteMatchModeRegEx) + int32_t m_filenameLen; // Length of Filename-string (m_szFilename), following to this record + int32_t m_nameLen; // Length of Name-string (m_szName), following to this record + int32_t m_destDirLen; // Length of DestDir-string (m_szDestDir), following to this record + int32_t m_categoryLen; // Length of Category-string (m_szCategory), following to this record + int32_t m_queuedFilenameLen; // Length of queued file name (m_szQueuedFilename), following to this record //char m_szFilename[m_iFilenameLen]; // variable sized //char m_szName[m_iNameLen]; // variable sized //char m_szDestDir[m_iDestDirLen]; // variable sized @@ -197,9 +197,9 @@ struct SNZBListResponseNZBEntry // A list response pp-parameter entry struct SNZBListResponsePPPEntry { - int32_t m_iNZBIndex; // Index of NZB-Entry in m_NZBEntries-list - int32_t m_iNameLen; // Length of Name-string (m_szName), following to this record - int32_t m_iValueLen; // Length of Value-string (m_szValue), following to this record + int32_t m_nzbIndex; // Index of NZB-Entry in m_NZBEntries-list + int32_t m_nameLen; // Length of Name-string (m_szName), following to this record + int32_t m_valueLen; // Length of Value-string (m_szValue), following to this record //char m_szName[m_iNameLen]; // variable sized //char m_szValue[m_iValueLen]; // variable sized }; @@ -207,18 +207,18 @@ struct SNZBListResponsePPPEntry // A list response file entry struct SNZBListResponseFileEntry { - int32_t m_iID; // Entry-ID - int32_t m_iNZBIndex; // Index of NZB-Entry in m_NZBEntries-list - int32_t m_iFileSizeLo; // Filesize in bytes, Low 32-bits of 64-bit value - int32_t m_iFileSizeHi; // Filesize in bytes, High 32-bits of 64-bit value - int32_t m_iRemainingSizeLo; // Remaining size in bytes, Low 32-bits of 64-bit value - int32_t m_iRemainingSizeHi; // Remaining size in bytes, High 32-bits of 64-bit value - int32_t m_bPaused; // 1 - file is paused - int32_t m_bFilenameConfirmed; // 1 - Filename confirmed (read from article body), 0 - Filename parsed from subject (can be changed after reading of article) - int32_t m_iActiveDownloads; // Number of active downloads for this file - int32_t m_bMatch; // 1 - file matches the pattern (only when Request has eRemoteMatchModeRegEx) - int32_t m_iSubjectLen; // Length of Subject-string (m_szSubject), following to this record - int32_t m_iFilenameLen; // Length of Filename-string (m_szFilename), following to this record + int32_t m_id; // Entry-ID + int32_t m_nzbIndex; // Index of NZB-Entry in m_NZBEntries-list + int32_t m_fileSizeLo; // Filesize in bytes, Low 32-bits of 64-bit value + int32_t m_fileSizeHi; // Filesize in bytes, High 32-bits of 64-bit value + int32_t m_remainingSizeLo; // Remaining size in bytes, Low 32-bits of 64-bit value + int32_t m_remainingSizeHi; // Remaining size in bytes, High 32-bits of 64-bit value + int32_t m_paused; // 1 - file is paused + int32_t m_filenameConfirmed; // 1 - Filename confirmed (read from article body), 0 - Filename parsed from subject (can be changed after reading of article) + int32_t m_activeDownloads; // Number of active downloads for this file + int32_t m_match; // 1 - file matches the pattern (only when Request has eRemoteMatchModeRegEx) + int32_t m_subjectLen; // Length of Subject-string (m_szSubject), following to this record + int32_t m_filenameLen; // Length of Filename-string (m_szFilename), following to this record //char m_szSubject[m_iSubjectLen]; // variable sized //char m_szFilename[m_iFilenameLen]; // variable sized }; @@ -226,76 +226,76 @@ struct SNZBListResponseFileEntry // A log request struct SNZBLogRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_iIDFrom; // Only one of these two parameters - int32_t m_iLines; // can be set. The another one must be set to "0". + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_idFrom; // Only one of these two parameters + int32_t m_lines; // can be set. The another one must be set to "0". }; // A log response struct SNZBLogResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_iEntrySize; // Size of the SNZBLogResponseEntry-struct - int32_t m_iNrTrailingEntries; // Number of Log-entries, following to this structure - int32_t m_iTrailingDataLength; // Length of all Log-entries, following to this structure + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_entrySize; // Size of the SNZBLogResponseEntry-struct + int32_t m_nrTrailingEntries; // Number of Log-entries, following to this structure + int32_t m_trailingDataLength; // Length of all Log-entries, following to this structure // SNZBLogResponseEntry m_Entries[m_iNrTrailingEntries] // variable sized }; // A log response entry struct SNZBLogResponseEntry { - int32_t m_iID; // ID of Log-entry - int32_t m_iKind; // see Message::Kind in "Log.h" - int32_t m_tTime; // time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. - int32_t m_iTextLen; // Length of Text-string (m_szText), following to this record + int32_t m_id; // ID of Log-entry + int32_t m_kind; // see Message::Kind in "Log.h" + int32_t m_time; // time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. + int32_t m_textLen; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTextLen]; // variable sized }; // A Pause/Unpause request struct SNZBPauseUnpauseRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_bPause; // 1 - server must be paused, 0 - server must be unpaused - int32_t m_iAction; // Action to be executed, see enum eRemotePauseUnpauseAction + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_pause; // 1 - server must be paused, 0 - server must be unpaused + int32_t m_action; // Action to be executed, see enum eRemotePauseUnpauseAction }; // A Pause/Unpause response struct SNZBPauseUnpauseResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // Request setting the download rate struct SNZBSetDownloadRateRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_iDownloadRate; // Speed limit, in Bytes pro Second + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_downloadRate; // Speed limit, in Bytes pro Second }; // A setting download rate response struct SNZBSetDownloadRateResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // edit queue request struct SNZBEditQueueRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_iAction; // Action to be executed, see enum DownloadQueue::EEditAction - int32_t m_iOffset; // Offset to move (for m_iAction = 0) - int32_t m_iMatchMode; // File/Group match mode, see enum eRemoteMatchMode - int32_t m_iNrTrailingIDEntries; // Number of ID-entries, following to this structure - int32_t m_iNrTrailingNameEntries; // Number of Name-entries, following to this structure - int32_t m_iTrailingNameEntriesLen; // Length of all Name-entries, following to this structure - int32_t m_iTextLen; // Length of Text-string (m_szText), following to this record - int32_t m_iTrailingDataLength; // Length of Text-string and all ID-entries, following to this structure + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_action; // Action to be executed, see enum DownloadQueue::EEditAction + int32_t m_offset; // Offset to move (for m_iAction = 0) + int32_t m_matchMode; // File/Group match mode, see enum eRemoteMatchMode + int32_t m_nrTrailingIdEntries; // Number of ID-entries, following to this structure + int32_t m_nrTrailingNameEntries; // Number of Name-entries, following to this structure + int32_t m_trailingNameEntriesLen; // Length of all Name-entries, following to this structure + int32_t m_textLen; // Length of Text-string (m_szText), following to this record + int32_t m_trailingDataLength; // Length of Text-string and all ID-entries, following to this structure //char m_szText[m_iTextLen]; // variable sized //int32_t m_iIDs[m_iNrTrailingIDEntries]; // variable sized array of IDs. For File-Actions - ID of file, for Group-Actions - ID of any file belonging to group //char* m_szNames[m_iNrTrailingNameEntries]; // variable sized array of strings. For File-Actions - name of file incl. nzb-name as path, for Group-Actions - name of group @@ -304,101 +304,101 @@ struct SNZBEditQueueRequest // An edit queue response struct SNZBEditQueueResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // Request dumping of debug info struct SNZBDumpDebugRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct + SNZBRequestBase m_messageBase; // Must be the first in the struct }; // Dumping of debug response struct SNZBDumpDebugResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // Shutdown server request struct SNZBShutdownRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct + SNZBRequestBase m_messageBase; // Must be the first in the struct }; // Shutdown server response struct SNZBShutdownResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // Reload server request struct SNZBReloadRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct + SNZBRequestBase m_messageBase; // Must be the first in the struct }; // Reload server response struct SNZBReloadResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // Server version request struct SNZBVersionRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct + SNZBRequestBase m_messageBase; // Must be the first in the struct }; // Server version response struct SNZBVersionResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // PostQueue request struct SNZBPostQueueRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct + SNZBRequestBase m_messageBase; // Must be the first in the struct }; // A PostQueue response struct SNZBPostQueueResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_iEntrySize; // Size of the SNZBPostQueueResponseEntry-struct - int32_t m_iNrTrailingEntries; // Number of PostQueue-entries, following to this structure - int32_t m_iTrailingDataLength; // Length of all PostQueue-entries, following to this structure + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_entrySize; // Size of the SNZBPostQueueResponseEntry-struct + int32_t m_nrTrailingEntries; // Number of PostQueue-entries, following to this structure + int32_t m_trailingDataLength; // Length of all PostQueue-entries, following to this structure // SNZBPostQueueResponseEntry m_Entries[m_iNrTrailingEntries] // variable sized }; // A PostQueue response entry struct SNZBPostQueueResponseEntry { - int32_t m_iID; // ID of Post-entry - int32_t m_iStage; // See PrePostProcessor::EPostJobStage - int32_t m_iStageProgress; // Progress of current stage, value in range 0..1000 - int32_t m_iFileProgress; // Progress of current file, value in range 0..1000 - int32_t m_iTotalTimeSec; // Number of seconds this post-job is beeing processed (after it first changed the state from QUEUED). - int32_t m_iStageTimeSec; // Number of seconds the current stage is beeing processed. - int32_t m_iNZBFilenameLen; // Length of NZBFileName-string (m_szNZBFilename), following to this record - int32_t m_iInfoNameLen; // Length of Filename-string (m_szFilename), following to this record - int32_t m_iDestDirLen; // Length of DestDir-string (m_szDestDir), following to this record - int32_t m_iProgressLabelLen; // Length of ProgressLabel-string (m_szProgressLabel), following to this record + int32_t m_id; // ID of Post-entry + int32_t m_stage; // See PrePostProcessor::EPostJobStage + int32_t m_stageProgress; // Progress of current stage, value in range 0..1000 + int32_t m_fileProgress; // Progress of current file, value in range 0..1000 + int32_t m_totalTimeSec; // Number of seconds this post-job is beeing processed (after it first changed the state from QUEUED). + int32_t m_stageTimeSec; // Number of seconds the current stage is beeing processed. + int32_t m_nzbFilenameLen; // Length of NZBFileName-string (m_szNZBFilename), following to this record + int32_t m_infoNameLen; // Length of Filename-string (m_szFilename), following to this record + int32_t m_destDirLen; // Length of DestDir-string (m_szDestDir), following to this record + int32_t m_progressLabelLen; // Length of ProgressLabel-string (m_szProgressLabel), following to this record //char m_szNZBFilename[m_iNZBFilenameLen]; // variable sized, may contain full path (local path on client) or only filename //char m_szInfoName[m_iInfoNameLen]; // variable sized //char m_szDestDir[m_iDestDirLen]; // variable sized @@ -408,70 +408,70 @@ struct SNZBPostQueueResponseEntry // Write log request struct SNZBWriteLogRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_iKind; // see Message::Kind in "Log.h" - int32_t m_iTrailingDataLength; // Length of nzb-file in bytes + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_kind; // see Message::Kind in "Log.h" + int32_t m_trailingDataLength; // Length of nzb-file in bytes //char m_szText[m_iTrailingDataLength]; // variable sized }; // Write log response struct SNZBWriteLogResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // Scan nzb directory request struct SNZBScanRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_bSyncMode; // 0 - asynchronous Scan (the command returns immediately), 1 - synchronous Scan (the command returns when the scan is completed) + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_syncMode; // 0 - asynchronous Scan (the command returns immediately), 1 - synchronous Scan (the command returns when the scan is completed) }; // Scan nzb directory response struct SNZBScanResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_bSuccess; // 0 - command failed, 1 - command executed successfully - int32_t m_iTrailingDataLength; // Length of Text-string (m_szText), following to this record + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_success; // 0 - command failed, 1 - command executed successfully + int32_t m_trailingDataLength; // Length of Text-string (m_szText), following to this record //char m_szText[m_iTrailingDataLength]; // variable sized }; // A history request struct SNZBHistoryRequest { - SNZBRequestBase m_MessageBase; // Must be the first in the struct - int32_t m_bHidden; // 0 - only return visible records, 1 - also return hidden records + SNZBRequestBase m_messageBase; // Must be the first in the struct + int32_t m_hidden; // 0 - only return visible records, 1 - also return hidden records }; // history response struct SNZBHistoryResponse { - SNZBResponseBase m_MessageBase; // Must be the first in the struct - int32_t m_iEntrySize; // Size of the SNZBHistoryResponseEntry-struct - int32_t m_iNrTrailingEntries; // Number of History-entries, following to this structure - int32_t m_iTrailingDataLength; // Length of all History-entries, following to this structure + SNZBResponseBase m_messageBase; // Must be the first in the struct + int32_t m_entrySize; // Size of the SNZBHistoryResponseEntry-struct + int32_t m_nrTrailingEntries; // Number of History-entries, following to this structure + int32_t m_trailingDataLength; // Length of all History-entries, following to this structure // SNZBHistoryResponseEntry m_Entries[m_iNrTrailingEntries] // variable sized }; // history entry struct SNZBHistoryResponseEntry { - int32_t m_iID; // History-ID - int32_t m_iKind; // Kind of Item: 1 - Collection (NZB), 2 - URL, 3 - DUP (hidden record) - int32_t m_tTime; // When the item was added to history. time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. - int32_t m_iNicenameLen; // Length of Nicename-string (m_szNicename), following to this record + int32_t m_id; // History-ID + int32_t m_kind; // Kind of Item: 1 - Collection (NZB), 2 - URL, 3 - DUP (hidden record) + int32_t m_time; // When the item was added to history. time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. + int32_t m_nicenameLen; // Length of Nicename-string (m_szNicename), following to this record // for Collection and Dup items (m_iKind = 1 or 2) - int32_t m_iSizeLo; // Size of all files in bytes, Low 32-bits of 64-bit value - int32_t m_iSizeHi; // Size of all files in bytes, High 32-bits of 64-bit value + int32_t m_sizeLo; // Size of all files in bytes, Low 32-bits of 64-bit value + int32_t m_sizeHi; // Size of all files in bytes, High 32-bits of 64-bit value // for Collection items (m_iKind = 1) - int32_t m_iFileCount; // Initial number of files included in NZB-file - int32_t m_iParStatus; // See NZBInfo::EParStatus - int32_t m_iScriptStatus; // See NZBInfo::EScriptStatus + int32_t m_fileCount; // Initial number of files included in NZB-file + int32_t m_parStatus; // See NZBInfo::EParStatus + int32_t m_scriptStatus; // See NZBInfo::EScriptStatus // for URL items (m_iKind = 2) - int32_t m_iUrlStatus; // See NZBInfo::EUrlStatus + int32_t m_urlStatus; // See NZBInfo::EUrlStatus // trailing data //char m_szNicename[m_iNicenameLen]; // variable sized }; diff --git a/daemon/remote/RemoteClient.cpp b/daemon/remote/RemoteClient.cpp index c37e9564..96ebe058 100644 --- a/daemon/remote/RemoteClient.cpp +++ b/daemon/remote/RemoteClient.cpp @@ -53,8 +53,8 @@ RemoteClient::RemoteClient() { - m_pConnection = NULL; - m_bVerbose = true; + m_connection = NULL; + m_verbose = true; /* printf("sizeof(SNZBRequestBase)=%i\n", sizeof(SNZBRequestBase)); @@ -74,12 +74,12 @@ RemoteClient::RemoteClient() RemoteClient::~RemoteClient() { - delete m_pConnection; + delete m_connection; } void RemoteClient::printf(const char * msg,...) { - if (m_bVerbose) + if (m_verbose) { va_list ap; va_start(ap, msg); @@ -90,7 +90,7 @@ void RemoteClient::printf(const char * msg,...) void RemoteClient::perror(const char * msg) { - if (m_bVerbose) + if (m_verbose) { ::perror(msg); } @@ -98,30 +98,30 @@ void RemoteClient::perror(const char * msg) bool RemoteClient::InitConnection() { - const char* szControlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); + const char* controlIP = !strcmp(g_pOptions->GetControlIP(), "0.0.0.0") ? "127.0.0.1" : g_pOptions->GetControlIP(); // Create a connection to the server - m_pConnection = new Connection(szControlIP, g_pOptions->GetControlPort(), false); + m_connection = new Connection(controlIP, g_pOptions->GetControlPort(), false); - bool OK = m_pConnection->Connect(); + bool OK = m_connection->Connect(); if (!OK) { - printf("Unable to send request to nzbget-server at %s (port %i)\n", szControlIP, g_pOptions->GetControlPort()); + printf("Unable to send request to nzbget-server at %s (port %i)\n", controlIP, g_pOptions->GetControlPort()); } return OK; } -void RemoteClient::InitMessageBase(SNZBRequestBase* pMessageBase, int iRequest, int iSize) +void RemoteClient::InitMessageBase(SNZBRequestBase* messageBase, int request, int size) { - pMessageBase->m_iSignature = htonl(NZBMESSAGE_SIGNATURE); - pMessageBase->m_iType = htonl(iRequest); - pMessageBase->m_iStructSize = htonl(iSize); + messageBase->m_signature = htonl(NZBMESSAGE_SIGNATURE); + messageBase->m_type = htonl(request); + messageBase->m_structSize = htonl(size); - strncpy(pMessageBase->m_szUsername, g_pOptions->GetControlUsername(), NZBREQUESTPASSWORDSIZE - 1); - pMessageBase->m_szUsername[NZBREQUESTPASSWORDSIZE - 1] = '\0'; + strncpy(messageBase->m_username, g_pOptions->GetControlUsername(), NZBREQUESTPASSWORDSIZE - 1); + messageBase->m_username[NZBREQUESTPASSWORDSIZE - 1] = '\0'; - strncpy(pMessageBase->m_szPassword, g_pOptions->GetControlPassword(), NZBREQUESTPASSWORDSIZE - 1); - pMessageBase->m_szPassword[NZBREQUESTPASSWORDSIZE - 1] = '\0'; + strncpy(messageBase->m_password, g_pOptions->GetControlPassword(), NZBREQUESTPASSWORDSIZE - 1); + messageBase->m_password[NZBREQUESTPASSWORDSIZE - 1] = '\0'; } bool RemoteClient::ReceiveBoolResponse() @@ -132,19 +132,19 @@ bool RemoteClient::ReceiveBoolResponse() SNZBDownloadResponse BoolResponse; memset(&BoolResponse, 0, sizeof(BoolResponse)); - bool bRead = m_pConnection->Recv((char*)&BoolResponse, sizeof(BoolResponse)); - if (!bRead || - (int)ntohl(BoolResponse.m_MessageBase.m_iSignature) != (int)NZBMESSAGE_SIGNATURE || - ntohl(BoolResponse.m_MessageBase.m_iStructSize) != sizeof(BoolResponse)) + bool read = m_connection->Recv((char*)&BoolResponse, sizeof(BoolResponse)); + if (!read || + (int)ntohl(BoolResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || + ntohl(BoolResponse.m_messageBase.m_structSize) != sizeof(BoolResponse)) { printf("No response or invalid response (timeout, not nzbget-server or wrong nzbget-server version)\n"); return false; } - int iTextLen = ntohl(BoolResponse.m_iTrailingDataLength); - char* buf = (char*)malloc(iTextLen); - bRead = m_pConnection->Recv(buf, iTextLen); - if (!bRead) + int textLen = ntohl(BoolResponse.m_trailingDataLength); + char* buf = (char*)malloc(textLen); + read = m_connection->Recv(buf, textLen); + if (!read) { printf("No response or invalid response (timeout, not nzbget-server or wrong nzbget-server version)\n"); free(buf); @@ -153,194 +153,194 @@ bool RemoteClient::ReceiveBoolResponse() printf("server returned: %s\n", buf); free(buf); - return ntohl(BoolResponse.m_bSuccess); + return ntohl(BoolResponse.m_success); } /* * Sends a message to the running nzbget process. */ -bool RemoteClient::RequestServerDownload(const char* szNZBFilename, const char* szNZBContent, - const char* szCategory, bool bAddFirst, bool bAddPaused, int iPriority, - const char* szDupeKey, int iDupeMode, int iDupeScore) +bool RemoteClient::RequestServerDownload(const char* nzbFilename, const char* nzbContent, + const char* category, bool addFirst, bool addPaused, int priority, + const char* dupeKey, int dupeMode, int dupeScore) { // Read the file into the buffer - char* szBuffer = NULL; - int iLength = 0; - bool bIsUrl = !strncasecmp(szNZBContent, "http://", 6) || !strncasecmp(szNZBContent, "https://", 7); - if (bIsUrl) + char* buffer = NULL; + int length = 0; + bool isUrl = !strncasecmp(nzbContent, "http://", 6) || !strncasecmp(nzbContent, "https://", 7); + if (isUrl) { - iLength = strlen(szNZBContent) + 1; + length = strlen(nzbContent) + 1; } else { - if (!Util::LoadFileIntoBuffer(szNZBContent, &szBuffer, &iLength)) + if (!Util::LoadFileIntoBuffer(nzbContent, &buffer, &length)) { - printf("Could not load file %s\n", szNZBContent); + printf("Could not load file %s\n", nzbContent); return false; } - iLength--; + length--; } bool OK = InitConnection(); if (OK) { SNZBDownloadRequest DownloadRequest; - InitMessageBase(&DownloadRequest.m_MessageBase, eRemoteRequestDownload, sizeof(DownloadRequest)); - DownloadRequest.m_bAddFirst = htonl(bAddFirst); - DownloadRequest.m_bAddPaused = htonl(bAddPaused); - DownloadRequest.m_iPriority = htonl(iPriority); - DownloadRequest.m_iDupeMode = htonl(iDupeMode); - DownloadRequest.m_iDupeScore = htonl(iDupeScore); - DownloadRequest.m_iTrailingDataLength = htonl(iLength); + InitMessageBase(&DownloadRequest.m_messageBase, remoteRequestDownload, sizeof(DownloadRequest)); + DownloadRequest.m_addFirst = htonl(addFirst); + DownloadRequest.m_addPaused = htonl(addPaused); + DownloadRequest.m_priority = htonl(priority); + DownloadRequest.m_dupeMode = htonl(dupeMode); + DownloadRequest.m_dupeScore = htonl(dupeScore); + DownloadRequest.m_trailingDataLength = htonl(length); - DownloadRequest.m_szNZBFilename[0] = '\0'; - if (!Util::EmptyStr(szNZBFilename)) + DownloadRequest.m_nzbFilename[0] = '\0'; + if (!Util::EmptyStr(nzbFilename)) { - strncpy(DownloadRequest.m_szNZBFilename, szNZBFilename, NZBREQUESTFILENAMESIZE - 1); + strncpy(DownloadRequest.m_nzbFilename, nzbFilename, NZBREQUESTFILENAMESIZE - 1); } - else if (!bIsUrl) + else if (!isUrl) { - strncpy(DownloadRequest.m_szNZBFilename, szNZBContent, NZBREQUESTFILENAMESIZE - 1); + strncpy(DownloadRequest.m_nzbFilename, nzbContent, NZBREQUESTFILENAMESIZE - 1); } - DownloadRequest.m_szNZBFilename[NZBREQUESTFILENAMESIZE-1] = '\0'; + DownloadRequest.m_nzbFilename[NZBREQUESTFILENAMESIZE-1] = '\0'; - DownloadRequest.m_szCategory[0] = '\0'; - if (szCategory) + DownloadRequest.m_category[0] = '\0'; + if (category) { - strncpy(DownloadRequest.m_szCategory, szCategory, NZBREQUESTFILENAMESIZE - 1); + strncpy(DownloadRequest.m_category, category, NZBREQUESTFILENAMESIZE - 1); } - DownloadRequest.m_szCategory[NZBREQUESTFILENAMESIZE-1] = '\0'; + DownloadRequest.m_category[NZBREQUESTFILENAMESIZE-1] = '\0'; - DownloadRequest.m_szDupeKey[0] = '\0'; - if (!Util::EmptyStr(szDupeKey)) + DownloadRequest.m_dupeKey[0] = '\0'; + if (!Util::EmptyStr(dupeKey)) { - strncpy(DownloadRequest.m_szDupeKey, szDupeKey, NZBREQUESTFILENAMESIZE - 1); + strncpy(DownloadRequest.m_dupeKey, dupeKey, NZBREQUESTFILENAMESIZE - 1); } - DownloadRequest.m_szDupeKey[NZBREQUESTFILENAMESIZE-1] = '\0'; + DownloadRequest.m_dupeKey[NZBREQUESTFILENAMESIZE-1] = '\0'; - if (!m_pConnection->Send((char*)(&DownloadRequest), sizeof(DownloadRequest))) + if (!m_connection->Send((char*)(&DownloadRequest), sizeof(DownloadRequest))) { perror("m_pConnection->Send"); OK = false; } else { - m_pConnection->Send(bIsUrl ? szNZBContent : szBuffer, iLength); + m_connection->Send(isUrl ? nzbContent : buffer, length); OK = ReceiveBoolResponse(); - m_pConnection->Disconnect(); + m_connection->Disconnect(); } } // Cleanup - free(szBuffer); + free(buffer); return OK; } -void RemoteClient::BuildFileList(SNZBListResponse* pListResponse, const char* pTrailingData, DownloadQueue* pDownloadQueue) +void RemoteClient::BuildFileList(SNZBListResponse* listResponse, const char* trailingData, DownloadQueue* downloadQueue) { - if (ntohl(pListResponse->m_iTrailingDataLength) > 0) + if (ntohl(listResponse->m_trailingDataLength) > 0) { - const char* pBufPtr = pTrailingData; + const char* bufPtr = trailingData; // read nzb entries - for (unsigned int i = 0; i < ntohl(pListResponse->m_iNrTrailingNZBEntries); i++) + for (unsigned int i = 0; i < ntohl(listResponse->m_nrTrailingNzbEntries); i++) { - SNZBListResponseNZBEntry* pListAnswer = (SNZBListResponseNZBEntry*) pBufPtr; + SNZBListResponseNZBEntry* listAnswer = (SNZBListResponseNZBEntry*) bufPtr; - const char* szFileName = pBufPtr + sizeof(SNZBListResponseNZBEntry); - const char* szName = pBufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(pListAnswer->m_iFilenameLen); - const char* szDestDir = pBufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(pListAnswer->m_iFilenameLen) + - ntohl(pListAnswer->m_iNameLen); - const char* szCategory = pBufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(pListAnswer->m_iFilenameLen) + - ntohl(pListAnswer->m_iNameLen) + ntohl(pListAnswer->m_iDestDirLen); - const char* m_szQueuedFilename = pBufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(pListAnswer->m_iFilenameLen) + - ntohl(pListAnswer->m_iNameLen) + ntohl(pListAnswer->m_iDestDirLen) + ntohl(pListAnswer->m_iCategoryLen); + const char* fileName = bufPtr + sizeof(SNZBListResponseNZBEntry); + const char* name = bufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(listAnswer->m_filenameLen); + const char* destDir = bufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(listAnswer->m_filenameLen) + + ntohl(listAnswer->m_nameLen); + const char* category = bufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(listAnswer->m_filenameLen) + + ntohl(listAnswer->m_nameLen) + ntohl(listAnswer->m_destDirLen); + const char* m_queuedFilename = bufPtr + sizeof(SNZBListResponseNZBEntry) + ntohl(listAnswer->m_filenameLen) + + ntohl(listAnswer->m_nameLen) + ntohl(listAnswer->m_destDirLen) + ntohl(listAnswer->m_categoryLen); - MatchedNZBInfo* pNZBInfo = new MatchedNZBInfo(); - pNZBInfo->SetID(ntohl(pListAnswer->m_iID)); - pNZBInfo->SetKind((NZBInfo::EKind)ntohl(pListAnswer->m_iKind)); - pNZBInfo->SetSize(Util::JoinInt64(ntohl(pListAnswer->m_iSizeHi), ntohl(pListAnswer->m_iSizeLo))); - pNZBInfo->SetRemainingSize(Util::JoinInt64(ntohl(pListAnswer->m_iRemainingSizeHi), ntohl(pListAnswer->m_iRemainingSizeLo))); - pNZBInfo->SetPausedSize(Util::JoinInt64(ntohl(pListAnswer->m_iPausedSizeHi), ntohl(pListAnswer->m_iPausedSizeLo))); - pNZBInfo->SetPausedFileCount(ntohl(pListAnswer->m_iPausedCount)); - pNZBInfo->SetRemainingParCount(ntohl(pListAnswer->m_iRemainingParCount)); - pNZBInfo->SetFilename(szFileName); - pNZBInfo->SetName(szName); - pNZBInfo->SetDestDir(szDestDir); - pNZBInfo->SetCategory(szCategory); - pNZBInfo->SetQueuedFilename(m_szQueuedFilename); - pNZBInfo->SetPriority(ntohl(pListAnswer->m_iPriority)); - pNZBInfo->m_bMatch = ntohl(pListAnswer->m_bMatch); + MatchedNZBInfo* nzbInfo = new MatchedNZBInfo(); + nzbInfo->SetID(ntohl(listAnswer->m_id)); + nzbInfo->SetKind((NZBInfo::EKind)ntohl(listAnswer->m_kind)); + nzbInfo->SetSize(Util::JoinInt64(ntohl(listAnswer->m_sizeHi), ntohl(listAnswer->m_sizeLo))); + nzbInfo->SetRemainingSize(Util::JoinInt64(ntohl(listAnswer->m_remainingSizeHi), ntohl(listAnswer->m_remainingSizeLo))); + nzbInfo->SetPausedSize(Util::JoinInt64(ntohl(listAnswer->m_pausedSizeHi), ntohl(listAnswer->m_pausedSizeLo))); + nzbInfo->SetPausedFileCount(ntohl(listAnswer->m_pausedCount)); + nzbInfo->SetRemainingParCount(ntohl(listAnswer->m_remainingParCount)); + nzbInfo->SetFilename(fileName); + nzbInfo->SetName(name); + nzbInfo->SetDestDir(destDir); + nzbInfo->SetCategory(category); + nzbInfo->SetQueuedFilename(m_queuedFilename); + nzbInfo->SetPriority(ntohl(listAnswer->m_priority)); + nzbInfo->m_match = ntohl(listAnswer->m_match); - pDownloadQueue->GetQueue()->push_back(pNZBInfo); + downloadQueue->GetQueue()->push_back(nzbInfo); - pBufPtr += sizeof(SNZBListResponseNZBEntry) + ntohl(pListAnswer->m_iFilenameLen) + - ntohl(pListAnswer->m_iNameLen) + ntohl(pListAnswer->m_iDestDirLen) + - ntohl(pListAnswer->m_iCategoryLen) + ntohl(pListAnswer->m_iQueuedFilenameLen); + bufPtr += sizeof(SNZBListResponseNZBEntry) + ntohl(listAnswer->m_filenameLen) + + ntohl(listAnswer->m_nameLen) + ntohl(listAnswer->m_destDirLen) + + ntohl(listAnswer->m_categoryLen) + ntohl(listAnswer->m_queuedFilenameLen); } //read ppp entries - for (unsigned int i = 0; i < ntohl(pListResponse->m_iNrTrailingPPPEntries); i++) + for (unsigned int i = 0; i < ntohl(listResponse->m_nrTrailingPPPEntries); i++) { - SNZBListResponsePPPEntry* pListAnswer = (SNZBListResponsePPPEntry*) pBufPtr; + SNZBListResponsePPPEntry* listAnswer = (SNZBListResponsePPPEntry*) bufPtr; - const char* szName = pBufPtr + sizeof(SNZBListResponsePPPEntry); - const char* szValue = pBufPtr + sizeof(SNZBListResponsePPPEntry) + ntohl(pListAnswer->m_iNameLen); + const char* name = bufPtr + sizeof(SNZBListResponsePPPEntry); + const char* value = bufPtr + sizeof(SNZBListResponsePPPEntry) + ntohl(listAnswer->m_nameLen); - NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->at(ntohl(pListAnswer->m_iNZBIndex) - 1); - pNZBInfo->GetParameters()->SetParameter(szName, szValue); + NZBInfo* nzbInfo = downloadQueue->GetQueue()->at(ntohl(listAnswer->m_nzbIndex) - 1); + nzbInfo->GetParameters()->SetParameter(name, value); - pBufPtr += sizeof(SNZBListResponsePPPEntry) + ntohl(pListAnswer->m_iNameLen) + - ntohl(pListAnswer->m_iValueLen); + bufPtr += sizeof(SNZBListResponsePPPEntry) + ntohl(listAnswer->m_nameLen) + + ntohl(listAnswer->m_valueLen); } //read file entries - for (unsigned int i = 0; i < ntohl(pListResponse->m_iNrTrailingFileEntries); i++) + for (unsigned int i = 0; i < ntohl(listResponse->m_nrTrailingFileEntries); i++) { - SNZBListResponseFileEntry* pListAnswer = (SNZBListResponseFileEntry*) pBufPtr; + SNZBListResponseFileEntry* listAnswer = (SNZBListResponseFileEntry*) bufPtr; - const char* szSubject = pBufPtr + sizeof(SNZBListResponseFileEntry); - const char* szFileName = pBufPtr + sizeof(SNZBListResponseFileEntry) + ntohl(pListAnswer->m_iSubjectLen); + const char* subject = bufPtr + sizeof(SNZBListResponseFileEntry); + const char* fileName = bufPtr + sizeof(SNZBListResponseFileEntry) + ntohl(listAnswer->m_subjectLen); - MatchedFileInfo* pFileInfo = new MatchedFileInfo(); - pFileInfo->SetID(ntohl(pListAnswer->m_iID)); - pFileInfo->SetSize(Util::JoinInt64(ntohl(pListAnswer->m_iFileSizeHi), ntohl(pListAnswer->m_iFileSizeLo))); - pFileInfo->SetRemainingSize(Util::JoinInt64(ntohl(pListAnswer->m_iRemainingSizeHi), ntohl(pListAnswer->m_iRemainingSizeLo))); - pFileInfo->SetPaused(ntohl(pListAnswer->m_bPaused)); - pFileInfo->SetSubject(szSubject); - pFileInfo->SetFilename(szFileName); - pFileInfo->SetFilenameConfirmed(ntohl(pListAnswer->m_bFilenameConfirmed)); - pFileInfo->SetActiveDownloads(ntohl(pListAnswer->m_iActiveDownloads)); - pFileInfo->m_bMatch = ntohl(pListAnswer->m_bMatch); + MatchedFileInfo* fileInfo = new MatchedFileInfo(); + fileInfo->SetID(ntohl(listAnswer->m_id)); + fileInfo->SetSize(Util::JoinInt64(ntohl(listAnswer->m_fileSizeHi), ntohl(listAnswer->m_fileSizeLo))); + fileInfo->SetRemainingSize(Util::JoinInt64(ntohl(listAnswer->m_remainingSizeHi), ntohl(listAnswer->m_remainingSizeLo))); + fileInfo->SetPaused(ntohl(listAnswer->m_paused)); + fileInfo->SetSubject(subject); + fileInfo->SetFilename(fileName); + fileInfo->SetFilenameConfirmed(ntohl(listAnswer->m_filenameConfirmed)); + fileInfo->SetActiveDownloads(ntohl(listAnswer->m_activeDownloads)); + fileInfo->m_match = ntohl(listAnswer->m_match); - NZBInfo* pNZBInfo = pDownloadQueue->GetQueue()->at(ntohl(pListAnswer->m_iNZBIndex) - 1); - pFileInfo->SetNZBInfo(pNZBInfo); - pNZBInfo->GetFileList()->push_back(pFileInfo); + NZBInfo* nzbInfo = downloadQueue->GetQueue()->at(ntohl(listAnswer->m_nzbIndex) - 1); + fileInfo->SetNZBInfo(nzbInfo); + nzbInfo->GetFileList()->push_back(fileInfo); - pBufPtr += sizeof(SNZBListResponseFileEntry) + ntohl(pListAnswer->m_iSubjectLen) + - ntohl(pListAnswer->m_iFilenameLen); + bufPtr += sizeof(SNZBListResponseFileEntry) + ntohl(listAnswer->m_subjectLen) + + ntohl(listAnswer->m_filenameLen); } } } -bool RemoteClient::RequestServerList(bool bFiles, bool bGroups, const char* szPattern) +bool RemoteClient::RequestServerList(bool files, bool groups, const char* pattern) { if (!InitConnection()) return false; SNZBListRequest ListRequest; - InitMessageBase(&ListRequest.m_MessageBase, eRemoteRequestList, sizeof(ListRequest)); - ListRequest.m_bFileList = htonl(true); - ListRequest.m_bServerState = htonl(true); - ListRequest.m_iMatchMode = htonl(szPattern ? eRemoteMatchModeRegEx : eRemoteMatchModeID); - ListRequest.m_bMatchGroup = htonl(bGroups); - if (szPattern) + InitMessageBase(&ListRequest.m_messageBase, remoteRequestList, sizeof(ListRequest)); + ListRequest.m_fileList = htonl(true); + ListRequest.m_serverState = htonl(true); + ListRequest.m_matchMode = htonl(pattern ? remoteMatchModeRegEx : remoteMatchModeId); + ListRequest.m_matchGroup = htonl(groups); + if (pattern) { - strncpy(ListRequest.m_szPattern, szPattern, NZBREQUESTFILENAMESIZE - 1); - ListRequest.m_szPattern[NZBREQUESTFILENAMESIZE-1] = '\0'; + strncpy(ListRequest.m_pattern, pattern, NZBREQUESTFILENAMESIZE - 1); + ListRequest.m_pattern[NZBREQUESTFILENAMESIZE-1] = '\0'; } - if (!m_pConnection->Send((char*)(&ListRequest), sizeof(ListRequest))) + if (!m_connection->Send((char*)(&ListRequest), sizeof(ListRequest))) { perror("m_pConnection->Send"); return false; @@ -350,38 +350,38 @@ bool RemoteClient::RequestServerList(bool bFiles, bool bGroups, const char* szPa // Now listen for the returned list SNZBListResponse ListResponse; - bool bRead = m_pConnection->Recv((char*) &ListResponse, sizeof(ListResponse)); - if (!bRead || - (int)ntohl(ListResponse.m_MessageBase.m_iSignature) != (int)NZBMESSAGE_SIGNATURE || - ntohl(ListResponse.m_MessageBase.m_iStructSize) != sizeof(ListResponse)) + bool read = m_connection->Recv((char*) &ListResponse, sizeof(ListResponse)); + if (!read || + (int)ntohl(ListResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || + ntohl(ListResponse.m_messageBase.m_structSize) != sizeof(ListResponse)) { printf("No response or invalid response (timeout, not nzbget-server or wrong nzbget-server version)\n"); return false; } - char* pBuf = NULL; - if (ntohl(ListResponse.m_iTrailingDataLength) > 0) + char* buf = NULL; + if (ntohl(ListResponse.m_trailingDataLength) > 0) { - pBuf = (char*)malloc(ntohl(ListResponse.m_iTrailingDataLength)); - if (!m_pConnection->Recv(pBuf, ntohl(ListResponse.m_iTrailingDataLength))) + buf = (char*)malloc(ntohl(ListResponse.m_trailingDataLength)); + if (!m_connection->Recv(buf, ntohl(ListResponse.m_trailingDataLength))) { - free(pBuf); + free(buf); return false; } } - m_pConnection->Disconnect(); + m_connection->Disconnect(); - if (szPattern && !ListResponse.m_bRegExValid) + if (pattern && !ListResponse.m_regExValid) { printf("Error in regular expression\n"); - free(pBuf); + free(buf); return false; } - if (bFiles) + if (files) { - if (ntohl(ListResponse.m_iTrailingDataLength) == 0) + if (ntohl(ListResponse.m_trailingDataLength) == 0) { printf("Server has no files queued for download\n"); } @@ -390,94 +390,94 @@ bool RemoteClient::RequestServerList(bool bFiles, bool bGroups, const char* szPa printf("Queue List\n"); printf("-----------------------------------\n"); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - BuildFileList(&ListResponse, pBuf, pDownloadQueue); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + BuildFileList(&ListResponse, buf, downloadQueue); - long long lRemaining = 0; - long long lPaused = 0; - int iMatches = 0; - int iNrFileEntries = 0; + long long remaining = 0; + long long paused = 0; + int matches = 0; + int nrFileEntries = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; + FileInfo* fileInfo = *it2; - iNrFileEntries++; + nrFileEntries++; - char szCompleted[100]; - szCompleted[0] = '\0'; - if (pFileInfo->GetRemainingSize() < pFileInfo->GetSize()) + char completed[100]; + completed[0] = '\0'; + if (fileInfo->GetRemainingSize() < fileInfo->GetSize()) { - sprintf(szCompleted, ", %i%s", (int)(100 - pFileInfo->GetRemainingSize() * 100 / pFileInfo->GetSize()), "%"); + sprintf(completed, ", %i%s", (int)(100 - fileInfo->GetRemainingSize() * 100 / fileInfo->GetSize()), "%"); } - char szThreads[100]; - szThreads[0] = '\0'; - if (pFileInfo->GetActiveDownloads() > 0) + char threads[100]; + threads[0] = '\0'; + if (fileInfo->GetActiveDownloads() > 0) { - sprintf(szThreads, ", %i thread%s", pFileInfo->GetActiveDownloads(), (pFileInfo->GetActiveDownloads() > 1 ? "s" : "")); + sprintf(threads, ", %i thread%s", fileInfo->GetActiveDownloads(), (fileInfo->GetActiveDownloads() > 1 ? "s" : "")); } - char szStatus[100]; - if (pFileInfo->GetPaused()) + char status[100]; + if (fileInfo->GetPaused()) { - sprintf(szStatus, " (paused)"); - lPaused += pFileInfo->GetRemainingSize(); + sprintf(status, " (paused)"); + paused += fileInfo->GetRemainingSize(); } else { - szStatus[0] = '\0'; - lRemaining += pFileInfo->GetRemainingSize(); + status[0] = '\0'; + remaining += fileInfo->GetRemainingSize(); } - if (!szPattern || ((MatchedFileInfo*)pFileInfo)->m_bMatch) + if (!pattern || ((MatchedFileInfo*)fileInfo)->m_match) { - char szSize[20]; - printf("[%i] %s/%s (%s%s%s)%s\n", pFileInfo->GetID(), pFileInfo->GetNZBInfo()->GetName(), - pFileInfo->GetFilename(), - Util::FormatSize(szSize, sizeof(szSize), pFileInfo->GetSize()), - szCompleted, szThreads, szStatus); - iMatches++; + char size[20]; + printf("[%i] %s/%s (%s%s%s)%s\n", fileInfo->GetID(), fileInfo->GetNZBInfo()->GetName(), + fileInfo->GetFilename(), + Util::FormatSize(size, sizeof(size), fileInfo->GetSize()), + completed, threads, status); + matches++; } } } DownloadQueue::Unlock(); - if (iMatches == 0) + if (matches == 0) { printf("No matches founds\n"); } printf("-----------------------------------\n"); - printf("Files: %i\n", iNrFileEntries); - if (szPattern) + printf("Files: %i\n", nrFileEntries); + if (pattern) { - printf("Matches: %i\n", iMatches); + printf("Matches: %i\n", matches); } - if (lPaused > 0) + if (paused > 0) { - char szRemaining[20]; - char szPausedSize[20]; + char remainingBuf[20]; + char pausedSizeBuf[20]; printf("Remaining size: %s (+%s paused)\n", - Util::FormatSize(szRemaining, sizeof(szRemaining), lRemaining), - Util::FormatSize(szPausedSize, sizeof(szPausedSize), lPaused)); + Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining), + Util::FormatSize(pausedSizeBuf, sizeof(pausedSizeBuf), paused)); } else { - char szRemaining[20]; - printf("Remaining size: %s\n", Util::FormatSize(szRemaining, sizeof(szRemaining), lRemaining)); + char remainingBuf[20]; + printf("Remaining size: %s\n", Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining)); } } } - if (bGroups) + if (groups) { - if (ntohl(ListResponse.m_iTrailingDataLength) == 0) + if (ntohl(ListResponse.m_trailingDataLength) == 0) { printf("Server has no files queued for download\n"); } @@ -486,238 +486,238 @@ bool RemoteClient::RequestServerList(bool bFiles, bool bGroups, const char* szPa printf("Queue List\n"); printf("-----------------------------------\n"); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - BuildFileList(&ListResponse, pBuf, pDownloadQueue); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + BuildFileList(&ListResponse, buf, downloadQueue); - long long lRemaining = 0; - long long lPaused = 0; - int iMatches = 0; - int iNrFileEntries = 0; + long long remaining = 0; + long long paused = 0; + int matches = 0; + int nrFileEntries = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; + NZBInfo* nzbInfo = *it; - iNrFileEntries += pNZBInfo->GetFileList()->size(); + nrFileEntries += nzbInfo->GetFileList()->size(); - long long lUnpausedRemainingSize = pNZBInfo->GetRemainingSize() - pNZBInfo->GetPausedSize(); - lRemaining += lUnpausedRemainingSize; + long long unpausedRemainingSize = nzbInfo->GetRemainingSize() - nzbInfo->GetPausedSize(); + remaining += unpausedRemainingSize; - char szRemaining[20]; - Util::FormatSize(szRemaining, sizeof(szRemaining), lUnpausedRemainingSize); + char remainingStr[20]; + Util::FormatSize(remainingStr, sizeof(remainingStr), unpausedRemainingSize); - char szPriority[100]; - szPriority[0] = '\0'; - if (pNZBInfo->GetPriority() != 0) + char priority[100]; + priority[0] = '\0'; + if (nzbInfo->GetPriority() != 0) { - sprintf(szPriority, "[%+i] ", pNZBInfo->GetPriority()); + sprintf(priority, "[%+i] ", nzbInfo->GetPriority()); } - char szPaused[20]; - szPaused[0] = '\0'; - if (pNZBInfo->GetPausedSize() > 0) + char pausedStr[20]; + pausedStr[0] = '\0'; + if (nzbInfo->GetPausedSize() > 0) { - char szPausedSize[20]; - Util::FormatSize(szPausedSize, sizeof(szPausedSize), pNZBInfo->GetPausedSize()); - sprintf(szPaused, " + %s paused", szPausedSize); - lPaused += pNZBInfo->GetPausedSize(); + char pausedSize[20]; + Util::FormatSize(pausedSize, sizeof(pausedSize), nzbInfo->GetPausedSize()); + sprintf(pausedStr, " + %s paused", pausedSize); + paused += nzbInfo->GetPausedSize(); } - char szCategory[1024]; - szCategory[0] = '\0'; - if (pNZBInfo->GetCategory() && strlen(pNZBInfo->GetCategory()) > 0) + char category[1024]; + category[0] = '\0'; + if (nzbInfo->GetCategory() && strlen(nzbInfo->GetCategory()) > 0) { - sprintf(szCategory, " (%s)", pNZBInfo->GetCategory()); + sprintf(category, " (%s)", nzbInfo->GetCategory()); } - char szThreads[100]; - szThreads[0] = '\0'; - if (pNZBInfo->GetActiveDownloads() > 0) + char threads[100]; + threads[0] = '\0'; + if (nzbInfo->GetActiveDownloads() > 0) { - sprintf(szThreads, ", %i thread%s", pNZBInfo->GetActiveDownloads(), (pNZBInfo->GetActiveDownloads() > 1 ? "s" : "")); + sprintf(threads, ", %i thread%s", nzbInfo->GetActiveDownloads(), (nzbInfo->GetActiveDownloads() > 1 ? "s" : "")); } - char szParameters[1024]; - szParameters[0] = '\0'; - for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++) + char parameters[1024]; + parameters[0] = '\0'; + for (NZBParameterList::iterator it = nzbInfo->GetParameters()->begin(); it != nzbInfo->GetParameters()->end(); it++) { - if (szParameters[0] == '\0') + if (parameters[0] == '\0') { - strncat(szParameters, " (", sizeof(szParameters) - strlen(szParameters) - 1); + strncat(parameters, " (", sizeof(parameters) - strlen(parameters) - 1); } else { - strncat(szParameters, ", ", sizeof(szParameters) - strlen(szParameters) - 1); + strncat(parameters, ", ", sizeof(parameters) - strlen(parameters) - 1); } - NZBParameter* pNZBParameter = *it; - strncat(szParameters, pNZBParameter->GetName(), sizeof(szParameters) - strlen(szParameters) - 1); - strncat(szParameters, "=", sizeof(szParameters) - strlen(szParameters) - 1); - strncat(szParameters, pNZBParameter->GetValue(), sizeof(szParameters) - strlen(szParameters) - 1); + NZBParameter* nzbParameter = *it; + strncat(parameters, nzbParameter->GetName(), sizeof(parameters) - strlen(parameters) - 1); + strncat(parameters, "=", sizeof(parameters) - strlen(parameters) - 1); + strncat(parameters, nzbParameter->GetValue(), sizeof(parameters) - strlen(parameters) - 1); } - if (szParameters[0] != '\0') + if (parameters[0] != '\0') { - strncat(szParameters, ")", sizeof(szParameters) - strlen(szParameters) - 1); + strncat(parameters, ")", sizeof(parameters) - strlen(parameters) - 1); } - char szUrlOrFile[100]; - if (pNZBInfo->GetKind() == NZBInfo::nkUrl) + char urlOrFile[100]; + if (nzbInfo->GetKind() == NZBInfo::nkUrl) { - strncpy(szUrlOrFile, "URL", sizeof(szUrlOrFile)); + strncpy(urlOrFile, "URL", sizeof(urlOrFile)); } else { - snprintf(szUrlOrFile, sizeof(szUrlOrFile), "%i file%s", (int)pNZBInfo->GetFileList()->size(), - pNZBInfo->GetFileList()->size() > 1 ? "s" : ""); - szUrlOrFile[100-1] = '\0'; + snprintf(urlOrFile, sizeof(urlOrFile), "%i file%s", (int)nzbInfo->GetFileList()->size(), + nzbInfo->GetFileList()->size() > 1 ? "s" : ""); + urlOrFile[100-1] = '\0'; } - if (!szPattern || ((MatchedNZBInfo*)pNZBInfo)->m_bMatch) + if (!pattern || ((MatchedNZBInfo*)nzbInfo)->m_match) { - printf("[%i] %s%s (%s, %s%s%s)%s%s\n", pNZBInfo->GetID(), szPriority, - pNZBInfo->GetName(), szUrlOrFile, szRemaining, - szPaused, szThreads, szCategory, szParameters); - iMatches++; + printf("[%i] %s%s (%s, %s%s%s)%s%s\n", nzbInfo->GetID(), priority, + nzbInfo->GetName(), urlOrFile, remainingStr, + pausedStr, threads, category, parameters); + matches++; } } - if (iMatches == 0) + if (matches == 0) { printf("No matches founds\n"); } printf("-----------------------------------\n"); - printf("Groups: %i\n", pDownloadQueue->GetQueue()->size()); - if (szPattern) + printf("Groups: %i\n", downloadQueue->GetQueue()->size()); + if (pattern) { - printf("Matches: %i\n", iMatches); + printf("Matches: %i\n", matches); } - printf("Files: %i\n", iNrFileEntries); + printf("Files: %i\n", nrFileEntries); - if (lPaused > 0) + if (paused > 0) { - char szRemaining[20]; - char szPausedSize[20]; + char remainingBuf[20]; + char pausedSizeBuf[20]; printf("Remaining size: %s (+%s paused)\n", - Util::FormatSize(szRemaining, sizeof(szRemaining), lRemaining), - Util::FormatSize(szPausedSize, sizeof(szPausedSize), lPaused)); + Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining), + Util::FormatSize(pausedSizeBuf, sizeof(pausedSizeBuf), paused)); } else { - char szRemaining[20]; + char remainingBuf[20]; printf("Remaining size: %s\n", - Util::FormatSize(szRemaining, sizeof(szRemaining), lRemaining)); + Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining)); } DownloadQueue::Unlock(); } } - free(pBuf); + free(buf); - long long lRemaining = Util::JoinInt64(ntohl(ListResponse.m_iRemainingSizeHi), ntohl(ListResponse.m_iRemainingSizeLo)); + long long remaining = Util::JoinInt64(ntohl(ListResponse.m_remainingSizeHi), ntohl(ListResponse.m_remainingSizeLo)); - if (!bFiles && !bGroups) + if (!files && !groups) { - char szRemaining[20]; - printf("Remaining size: %s\n", Util::FormatSize(szRemaining, sizeof(szRemaining), lRemaining)); + char remainingBuf[20]; + printf("Remaining size: %s\n", Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining)); } - if (ntohl(ListResponse.m_iDownloadRate) > 0 && - !ntohl(ListResponse.m_bDownloadPaused) && - !ntohl(ListResponse.m_bDownload2Paused) && - !ntohl(ListResponse.m_bDownloadStandBy)) + if (ntohl(ListResponse.m_downloadRate) > 0 && + !ntohl(ListResponse.m_downloadPaused) && + !ntohl(ListResponse.m_download2Paused) && + !ntohl(ListResponse.m_downloadStandBy)) { - long long remain_sec = (long long)(lRemaining / ntohl(ListResponse.m_iDownloadRate)); + long long remain_sec = (long long)(remaining / ntohl(ListResponse.m_downloadRate)); int h = (int)(remain_sec / 3600); int m = (int)((remain_sec % 3600) / 60); int s = (int)(remain_sec % 60); printf("Remaining time: %.2d:%.2d:%.2d\n", h, m, s); } - char szSpeed[20]; + char speed[20]; printf("Current download rate: %s\n", - Util::FormatSpeed(szSpeed, sizeof(szSpeed), ntohl(ListResponse.m_iDownloadRate))); + Util::FormatSpeed(speed, sizeof(speed), ntohl(ListResponse.m_downloadRate))); - long long iAllBytes = Util::JoinInt64(ntohl(ListResponse.m_iDownloadedBytesHi), ntohl(ListResponse.m_iDownloadedBytesLo)); - int iAverageSpeed = (int)(ntohl(ListResponse.m_iDownloadTimeSec) > 0 ? iAllBytes / ntohl(ListResponse.m_iDownloadTimeSec) : 0); - printf("Session download rate: %s\n", Util::FormatSpeed(szSpeed, sizeof(szSpeed), iAverageSpeed)); + long long allBytes = Util::JoinInt64(ntohl(ListResponse.m_downloadedBytesHi), ntohl(ListResponse.m_downloadedBytesLo)); + int averageSpeed = (int)(ntohl(ListResponse.m_downloadTimeSec) > 0 ? allBytes / ntohl(ListResponse.m_downloadTimeSec) : 0); + printf("Session download rate: %s\n", Util::FormatSpeed(speed, sizeof(speed), averageSpeed)); - if (ntohl(ListResponse.m_iDownloadLimit) > 0) + if (ntohl(ListResponse.m_downloadLimit) > 0) { printf("Speed limit: %s\n", - Util::FormatSpeed(szSpeed, sizeof(szSpeed), ntohl(ListResponse.m_iDownloadLimit))); + Util::FormatSpeed(speed, sizeof(speed), ntohl(ListResponse.m_downloadLimit))); } - int sec = ntohl(ListResponse.m_iUpTimeSec); + int sec = ntohl(ListResponse.m_upTimeSec); int h = sec / 3600; int m = (sec % 3600) / 60; int s = sec % 60; printf("Up time: %.2d:%.2d:%.2d\n", h, m, s); - sec = ntohl(ListResponse.m_iDownloadTimeSec); + sec = ntohl(ListResponse.m_downloadTimeSec); h = sec / 3600; m = (sec % 3600) / 60; s = sec % 60; printf("Download time: %.2d:%.2d:%.2d\n", h, m, s); - char szSize[20]; - printf("Downloaded: %s\n", Util::FormatSize(szSize, sizeof(szSize), iAllBytes)); + char size[20]; + printf("Downloaded: %s\n", Util::FormatSize(size, sizeof(size), allBytes)); - printf("Threads running: %i\n", ntohl(ListResponse.m_iThreadCount)); + printf("Threads running: %i\n", ntohl(ListResponse.m_threadCount)); - if (ntohl(ListResponse.m_iPostJobCount) > 0) + if (ntohl(ListResponse.m_postJobCount) > 0) { - printf("Post-jobs: %i\n", (int)ntohl(ListResponse.m_iPostJobCount)); + printf("Post-jobs: %i\n", (int)ntohl(ListResponse.m_postJobCount)); } - if (ntohl(ListResponse.m_bScanPaused)) + if (ntohl(ListResponse.m_scanPaused)) { printf("Scan state: Paused\n"); } - char szServerState[50]; + char serverState[50]; - if (ntohl(ListResponse.m_bDownloadPaused) || ntohl(ListResponse.m_bDownload2Paused)) + if (ntohl(ListResponse.m_downloadPaused) || ntohl(ListResponse.m_download2Paused)) { - snprintf(szServerState, sizeof(szServerState), "%s%s", - ntohl(ListResponse.m_bDownloadStandBy) ? "Paused" : "Pausing", - ntohl(ListResponse.m_bDownloadPaused) && ntohl(ListResponse.m_bDownload2Paused) ? - " (+2)" : ntohl(ListResponse.m_bDownload2Paused) ? " (2)" : ""); + snprintf(serverState, sizeof(serverState), "%s%s", + ntohl(ListResponse.m_downloadStandBy) ? "Paused" : "Pausing", + ntohl(ListResponse.m_downloadPaused) && ntohl(ListResponse.m_download2Paused) ? + " (+2)" : ntohl(ListResponse.m_download2Paused) ? " (2)" : ""); } else { - snprintf(szServerState, sizeof(szServerState), "%s", ntohl(ListResponse.m_bDownloadStandBy) ? "" : "Downloading"); + snprintf(serverState, sizeof(serverState), "%s", ntohl(ListResponse.m_downloadStandBy) ? "" : "Downloading"); } - if (ntohl(ListResponse.m_iPostJobCount) > 0 || ntohl(ListResponse.m_bPostPaused)) + if (ntohl(ListResponse.m_postJobCount) > 0 || ntohl(ListResponse.m_postPaused)) { - strncat(szServerState, strlen(szServerState) > 0 ? ", Post-Processing" : "Post-Processing", sizeof(szServerState) - strlen(szServerState) - 1); - if (ntohl(ListResponse.m_bPostPaused)) + strncat(serverState, strlen(serverState) > 0 ? ", Post-Processing" : "Post-Processing", sizeof(serverState) - strlen(serverState) - 1); + if (ntohl(ListResponse.m_postPaused)) { - strncat(szServerState, " paused", sizeof(szServerState) - strlen(szServerState) - 1); + strncat(serverState, " paused", sizeof(serverState) - strlen(serverState) - 1); } } - if (strlen(szServerState) == 0) + if (strlen(serverState) == 0) { - strncpy(szServerState, "Stand-By", sizeof(szServerState)); + strncpy(serverState, "Stand-By", sizeof(serverState)); } - printf("Server state: %s\n", szServerState); + printf("Server state: %s\n", serverState); return true; } -bool RemoteClient::RequestServerLog(int iLines) +bool RemoteClient::RequestServerLog(int lines) { if (!InitConnection()) return false; SNZBLogRequest LogRequest; - InitMessageBase(&LogRequest.m_MessageBase, eRemoteRequestLog, sizeof(LogRequest)); - LogRequest.m_iLines = htonl(iLines); - LogRequest.m_iIDFrom = 0; + InitMessageBase(&LogRequest.m_messageBase, remoteRequestLog, sizeof(LogRequest)); + LogRequest.m_lines = htonl(lines); + LogRequest.m_idFrom = 0; - if (!m_pConnection->Send((char*)(&LogRequest), sizeof(LogRequest))) + if (!m_connection->Send((char*)(&LogRequest), sizeof(LogRequest))) { perror("m_pConnection->Send"); return false; @@ -727,112 +727,112 @@ bool RemoteClient::RequestServerLog(int iLines) // Now listen for the returned log SNZBLogResponse LogResponse; - bool bRead = m_pConnection->Recv((char*) &LogResponse, sizeof(LogResponse)); - if (!bRead || - (int)ntohl(LogResponse.m_MessageBase.m_iSignature) != (int)NZBMESSAGE_SIGNATURE || - ntohl(LogResponse.m_MessageBase.m_iStructSize) != sizeof(LogResponse)) + bool read = m_connection->Recv((char*) &LogResponse, sizeof(LogResponse)); + if (!read || + (int)ntohl(LogResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || + ntohl(LogResponse.m_messageBase.m_structSize) != sizeof(LogResponse)) { printf("No response or invalid response (timeout, not nzbget-server or wrong nzbget-server version)\n"); return false; } - char* pBuf = NULL; - if (ntohl(LogResponse.m_iTrailingDataLength) > 0) + char* buf = NULL; + if (ntohl(LogResponse.m_trailingDataLength) > 0) { - pBuf = (char*)malloc(ntohl(LogResponse.m_iTrailingDataLength)); - if (!m_pConnection->Recv(pBuf, ntohl(LogResponse.m_iTrailingDataLength))) + buf = (char*)malloc(ntohl(LogResponse.m_trailingDataLength)); + if (!m_connection->Recv(buf, ntohl(LogResponse.m_trailingDataLength))) { - free(pBuf); + free(buf); return false; } } - m_pConnection->Disconnect(); + m_connection->Disconnect(); - if (LogResponse.m_iTrailingDataLength == 0) + if (LogResponse.m_trailingDataLength == 0) { printf("Log is empty\n"); } else { - printf("Log (last %i entries)\n", ntohl(LogResponse.m_iNrTrailingEntries)); + printf("Log (last %i entries)\n", ntohl(LogResponse.m_nrTrailingEntries)); printf("-----------------------------------\n"); - char* pBufPtr = (char*)pBuf; - for (unsigned int i = 0; i < ntohl(LogResponse.m_iNrTrailingEntries); i++) + char* bufPtr = (char*)buf; + for (unsigned int i = 0; i < ntohl(LogResponse.m_nrTrailingEntries); i++) { - SNZBLogResponseEntry* pLogAnswer = (SNZBLogResponseEntry*) pBufPtr; + SNZBLogResponseEntry* logAnswer = (SNZBLogResponseEntry*) bufPtr; - char* szText = pBufPtr + sizeof(SNZBLogResponseEntry); - switch (ntohl(pLogAnswer->m_iKind)) + char* text = bufPtr + sizeof(SNZBLogResponseEntry); + switch (ntohl(logAnswer->m_kind)) { case Message::mkDebug: - printf("[DEBUG] %s\n", szText); + printf("[DEBUG] %s\n", text); break; case Message::mkError: - printf("[ERROR] %s\n", szText); + printf("[ERROR] %s\n", text); break; case Message::mkWarning: - printf("[WARNING] %s\n", szText); + printf("[WARNING] %s\n", text); break; case Message::mkInfo: - printf("[INFO] %s\n", szText); + printf("[INFO] %s\n", text); break; case Message::mkDetail: - printf("[DETAIL] %s\n", szText); + printf("[DETAIL] %s\n", text); break; } - pBufPtr += sizeof(SNZBLogResponseEntry) + ntohl(pLogAnswer->m_iTextLen); + bufPtr += sizeof(SNZBLogResponseEntry) + ntohl(logAnswer->m_textLen); } printf("-----------------------------------\n"); - free(pBuf); + free(buf); } return true; } -bool RemoteClient::RequestServerPauseUnpause(bool bPause, eRemotePauseUnpauseAction iAction) +bool RemoteClient::RequestServerPauseUnpause(bool pause, remotePauseUnpauseAction action) { if (!InitConnection()) return false; SNZBPauseUnpauseRequest PauseUnpauseRequest; - InitMessageBase(&PauseUnpauseRequest.m_MessageBase, eRemoteRequestPauseUnpause, sizeof(PauseUnpauseRequest)); - PauseUnpauseRequest.m_bPause = htonl(bPause); - PauseUnpauseRequest.m_iAction = htonl(iAction); + InitMessageBase(&PauseUnpauseRequest.m_messageBase, remoteRequestPauseUnpause, sizeof(PauseUnpauseRequest)); + PauseUnpauseRequest.m_pause = htonl(pause); + PauseUnpauseRequest.m_action = htonl(action); - if (!m_pConnection->Send((char*)(&PauseUnpauseRequest), sizeof(PauseUnpauseRequest))) + if (!m_connection->Send((char*)(&PauseUnpauseRequest), sizeof(PauseUnpauseRequest))) { perror("m_pConnection->Send"); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return false; } bool OK = ReceiveBoolResponse(); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } -bool RemoteClient::RequestServerSetDownloadRate(int iRate) +bool RemoteClient::RequestServerSetDownloadRate(int rate) { if (!InitConnection()) return false; SNZBSetDownloadRateRequest SetDownloadRateRequest; - InitMessageBase(&SetDownloadRateRequest.m_MessageBase, eRemoteRequestSetDownloadRate, sizeof(SetDownloadRateRequest)); - SetDownloadRateRequest.m_iDownloadRate = htonl(iRate); + InitMessageBase(&SetDownloadRateRequest.m_messageBase, remoteRequestSetDownloadRate, sizeof(SetDownloadRateRequest)); + SetDownloadRateRequest.m_downloadRate = htonl(rate); - if (!m_pConnection->Send((char*)(&SetDownloadRateRequest), sizeof(SetDownloadRateRequest))) + if (!m_connection->Send((char*)(&SetDownloadRateRequest), sizeof(SetDownloadRateRequest))) { perror("m_pConnection->Send"); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return false; } bool OK = ReceiveBoolResponse(); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } @@ -842,25 +842,25 @@ bool RemoteClient::RequestServerDumpDebug() if (!InitConnection()) return false; SNZBDumpDebugRequest DumpDebugInfo; - InitMessageBase(&DumpDebugInfo.m_MessageBase, eRemoteRequestDumpDebug, sizeof(DumpDebugInfo)); + InitMessageBase(&DumpDebugInfo.m_messageBase, remoteRequestDumpDebug, sizeof(DumpDebugInfo)); - if (!m_pConnection->Send((char*)(&DumpDebugInfo), sizeof(DumpDebugInfo))) + if (!m_connection->Send((char*)(&DumpDebugInfo), sizeof(DumpDebugInfo))) { perror("m_pConnection->Send"); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return false; } bool OK = ReceiveBoolResponse(); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } -bool RemoteClient::RequestServerEditQueue(DownloadQueue::EEditAction eAction, int iOffset, const char* szText, - int* pIDList, int iIDCount, NameList* pNameList, eRemoteMatchMode iMatchMode) +bool RemoteClient::RequestServerEditQueue(DownloadQueue::EEditAction action, int offset, const char* text, + int* idList, int idCount, NameList* nameList, remoteMatchMode matchMode) { - if ((iIDCount <= 0 || pIDList == NULL) && (pNameList == NULL || pNameList->size() == 0)) + if ((idCount <= 0 || idList == NULL) && (nameList == NULL || nameList->size() == 0)) { printf("File(s) not specified\n"); return false; @@ -868,80 +868,80 @@ bool RemoteClient::RequestServerEditQueue(DownloadQueue::EEditAction eAction, in if (!InitConnection()) return false; - int iIDLength = sizeof(int32_t) * iIDCount; + int idLength = sizeof(int32_t) * idCount; - int iNameCount = 0; - int iNameLength = 0; - if (pNameList && pNameList->size() > 0) + int nameCount = 0; + int nameLength = 0; + if (nameList && nameList->size() > 0) { - for (NameList::iterator it = pNameList->begin(); it != pNameList->end(); it++) + for (NameList::iterator it = nameList->begin(); it != nameList->end(); it++) { - const char *szName = *it; - iNameLength += strlen(szName) + 1; - iNameCount++; + const char *name = *it; + nameLength += strlen(name) + 1; + nameCount++; } // align size to 4-bytes, needed by ARM-processor (and may be others) - iNameLength += iNameLength % 4 > 0 ? 4 - iNameLength % 4 : 0; + nameLength += nameLength % 4 > 0 ? 4 - nameLength % 4 : 0; } - int iTextLen = szText ? strlen(szText) + 1 : 0; + int textLen = text ? strlen(text) + 1 : 0; // align size to 4-bytes, needed by ARM-processor (and may be others) - iTextLen += iTextLen % 4 > 0 ? 4 - iTextLen % 4 : 0; + textLen += textLen % 4 > 0 ? 4 - textLen % 4 : 0; - int iLength = iTextLen + iIDLength + iNameLength; + int length = textLen + idLength + nameLength; SNZBEditQueueRequest EditQueueRequest; - InitMessageBase(&EditQueueRequest.m_MessageBase, eRemoteRequestEditQueue, sizeof(EditQueueRequest)); - EditQueueRequest.m_iAction = htonl(eAction); - EditQueueRequest.m_iMatchMode = htonl(iMatchMode); - EditQueueRequest.m_iOffset = htonl((int)iOffset); - EditQueueRequest.m_iTextLen = htonl(iTextLen); - EditQueueRequest.m_iNrTrailingIDEntries = htonl(iIDCount); - EditQueueRequest.m_iNrTrailingNameEntries = htonl(iNameCount); - EditQueueRequest.m_iTrailingNameEntriesLen = htonl(iNameLength); - EditQueueRequest.m_iTrailingDataLength = htonl(iLength); + InitMessageBase(&EditQueueRequest.m_messageBase, remoteRequestEditQueue, sizeof(EditQueueRequest)); + EditQueueRequest.m_action = htonl(action); + EditQueueRequest.m_matchMode = htonl(matchMode); + EditQueueRequest.m_offset = htonl((int)offset); + EditQueueRequest.m_textLen = htonl(textLen); + EditQueueRequest.m_nrTrailingIdEntries = htonl(idCount); + EditQueueRequest.m_nrTrailingNameEntries = htonl(nameCount); + EditQueueRequest.m_trailingNameEntriesLen = htonl(nameLength); + EditQueueRequest.m_trailingDataLength = htonl(length); - char* pTrailingData = (char*)malloc(iLength); + char* trailingData = (char*)malloc(length); - if (iTextLen > 0) + if (textLen > 0) { - strcpy(pTrailingData, szText); + strcpy(trailingData, text); } - int32_t* pIDs = (int32_t*)(pTrailingData + iTextLen); + int32_t* ids = (int32_t*)(trailingData + textLen); - for (int i = 0; i < iIDCount; i++) + for (int i = 0; i < idCount; i++) { - pIDs[i] = htonl(pIDList[i]); + ids[i] = htonl(idList[i]); } - if (iNameCount > 0) + if (nameCount > 0) { - char *pNames = pTrailingData + iTextLen + iIDLength; - for (NameList::iterator it = pNameList->begin(); it != pNameList->end(); it++) + char *names = trailingData + textLen + idLength; + for (NameList::iterator it = nameList->begin(); it != nameList->end(); it++) { - const char *szName = *it; - int iLen = strlen(szName); - strncpy(pNames, szName, iLen + 1); - pNames += iLen + 1; + const char *name = *it; + int len = strlen(name); + strncpy(names, name, len + 1); + names += len + 1; } } bool OK = false; - if (!m_pConnection->Send((char*)(&EditQueueRequest), sizeof(EditQueueRequest))) + if (!m_connection->Send((char*)(&EditQueueRequest), sizeof(EditQueueRequest))) { perror("m_pConnection->Send"); } else { - m_pConnection->Send(pTrailingData, iLength); + m_connection->Send(trailingData, length); OK = ReceiveBoolResponse(); - m_pConnection->Disconnect(); + m_connection->Disconnect(); } - free(pTrailingData); + free(trailingData); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } @@ -950,9 +950,9 @@ bool RemoteClient::RequestServerShutdown() if (!InitConnection()) return false; SNZBShutdownRequest ShutdownRequest; - InitMessageBase(&ShutdownRequest.m_MessageBase, eRemoteRequestShutdown, sizeof(ShutdownRequest)); + InitMessageBase(&ShutdownRequest.m_messageBase, remoteRequestShutdown, sizeof(ShutdownRequest)); - bool OK = m_pConnection->Send((char*)(&ShutdownRequest), sizeof(ShutdownRequest)); + bool OK = m_connection->Send((char*)(&ShutdownRequest), sizeof(ShutdownRequest)); if (OK) { OK = ReceiveBoolResponse(); @@ -962,7 +962,7 @@ bool RemoteClient::RequestServerShutdown() perror("m_pConnection->Send"); } - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } @@ -971,9 +971,9 @@ bool RemoteClient::RequestServerReload() if (!InitConnection()) return false; SNZBReloadRequest ReloadRequest; - InitMessageBase(&ReloadRequest.m_MessageBase, eRemoteRequestReload, sizeof(ReloadRequest)); + InitMessageBase(&ReloadRequest.m_messageBase, remoteRequestReload, sizeof(ReloadRequest)); - bool OK = m_pConnection->Send((char*)(&ReloadRequest), sizeof(ReloadRequest)); + bool OK = m_connection->Send((char*)(&ReloadRequest), sizeof(ReloadRequest)); if (OK) { OK = ReceiveBoolResponse(); @@ -983,7 +983,7 @@ bool RemoteClient::RequestServerReload() perror("m_pConnection->Send"); } - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } @@ -992,9 +992,9 @@ bool RemoteClient::RequestServerVersion() if (!InitConnection()) return false; SNZBVersionRequest VersionRequest; - InitMessageBase(&VersionRequest.m_MessageBase, eRemoteRequestVersion, sizeof(VersionRequest)); + InitMessageBase(&VersionRequest.m_messageBase, remoteRequestVersion, sizeof(VersionRequest)); - bool OK = m_pConnection->Send((char*)(&VersionRequest), sizeof(VersionRequest)); + bool OK = m_connection->Send((char*)(&VersionRequest), sizeof(VersionRequest)); if (OK) { OK = ReceiveBoolResponse(); @@ -1004,7 +1004,7 @@ bool RemoteClient::RequestServerVersion() perror("m_pConnection->Send"); } - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } @@ -1013,9 +1013,9 @@ bool RemoteClient::RequestPostQueue() if (!InitConnection()) return false; SNZBPostQueueRequest PostQueueRequest; - InitMessageBase(&PostQueueRequest.m_MessageBase, eRemoteRequestPostQueue, sizeof(PostQueueRequest)); + InitMessageBase(&PostQueueRequest.m_messageBase, remoteRequestPostQueue, sizeof(PostQueueRequest)); - if (!m_pConnection->Send((char*)(&PostQueueRequest), sizeof(PostQueueRequest))) + if (!m_connection->Send((char*)(&PostQueueRequest), sizeof(PostQueueRequest))) { perror("m_pConnection->Send"); return false; @@ -1025,29 +1025,29 @@ bool RemoteClient::RequestPostQueue() // Now listen for the returned list SNZBPostQueueResponse PostQueueResponse; - bool bRead = m_pConnection->Recv((char*) &PostQueueResponse, sizeof(PostQueueResponse)); - if (!bRead || - (int)ntohl(PostQueueResponse.m_MessageBase.m_iSignature) != (int)NZBMESSAGE_SIGNATURE || - ntohl(PostQueueResponse.m_MessageBase.m_iStructSize) != sizeof(PostQueueResponse)) + bool read = m_connection->Recv((char*) &PostQueueResponse, sizeof(PostQueueResponse)); + if (!read || + (int)ntohl(PostQueueResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || + ntohl(PostQueueResponse.m_messageBase.m_structSize) != sizeof(PostQueueResponse)) { printf("No response or invalid response (timeout, not nzbget-server or wrong nzbget-server version)\n"); return false; } - char* pBuf = NULL; - if (ntohl(PostQueueResponse.m_iTrailingDataLength) > 0) + char* buf = NULL; + if (ntohl(PostQueueResponse.m_trailingDataLength) > 0) { - pBuf = (char*)malloc(ntohl(PostQueueResponse.m_iTrailingDataLength)); - if (!m_pConnection->Recv(pBuf, ntohl(PostQueueResponse.m_iTrailingDataLength))) + buf = (char*)malloc(ntohl(PostQueueResponse.m_trailingDataLength)); + if (!m_connection->Recv(buf, ntohl(PostQueueResponse.m_trailingDataLength))) { - free(pBuf); + free(buf); return false; } } - m_pConnection->Disconnect(); + m_connection->Disconnect(); - if (ntohl(PostQueueResponse.m_iTrailingDataLength) == 0) + if (ntohl(PostQueueResponse.m_trailingDataLength) == 0) { printf("Server has no jobs queued for post-processing\n"); } @@ -1056,31 +1056,31 @@ bool RemoteClient::RequestPostQueue() printf("Post-Processing List\n"); printf("-----------------------------------\n"); - char* pBufPtr = (char*)pBuf; - for (unsigned int i = 0; i < ntohl(PostQueueResponse.m_iNrTrailingEntries); i++) + char* bufPtr = (char*)buf; + for (unsigned int i = 0; i < ntohl(PostQueueResponse.m_nrTrailingEntries); i++) { - SNZBPostQueueResponseEntry* pPostQueueAnswer = (SNZBPostQueueResponseEntry*) pBufPtr; + SNZBPostQueueResponseEntry* postQueueAnswer = (SNZBPostQueueResponseEntry*) bufPtr; - int iStageProgress = ntohl(pPostQueueAnswer->m_iStageProgress); + int stageProgress = ntohl(postQueueAnswer->m_stageProgress); - char szCompleted[100]; - szCompleted[0] = '\0'; - if (iStageProgress > 0 && (int)ntohl(pPostQueueAnswer->m_iStage) != (int)PostInfo::ptExecutingScript) + char completed[100]; + completed[0] = '\0'; + if (stageProgress > 0 && (int)ntohl(postQueueAnswer->m_stage) != (int)PostInfo::ptExecutingScript) { - sprintf(szCompleted, ", %i%s", (int)(iStageProgress / 10), "%"); + sprintf(completed, ", %i%s", (int)(stageProgress / 10), "%"); } - const char* szPostStageName[] = { "", ", Loading Pars", ", Verifying source files", ", Repairing", ", Verifying repaired files", ", Unpacking", ", Executing postprocess-script", "" }; - char* szInfoName = pBufPtr + sizeof(SNZBPostQueueResponseEntry) + ntohl(pPostQueueAnswer->m_iNZBFilenameLen); + const char* postStageName[] = { "", ", Loading Pars", ", Verifying source files", ", Repairing", ", Verifying repaired files", ", Unpacking", ", Executing postprocess-script", "" }; + char* infoName = bufPtr + sizeof(SNZBPostQueueResponseEntry) + ntohl(postQueueAnswer->m_nzbFilenameLen); - printf("[%i] %s%s%s\n", ntohl(pPostQueueAnswer->m_iID), szInfoName, szPostStageName[ntohl(pPostQueueAnswer->m_iStage)], szCompleted); + printf("[%i] %s%s%s\n", ntohl(postQueueAnswer->m_id), infoName, postStageName[ntohl(postQueueAnswer->m_stage)], completed); - pBufPtr += sizeof(SNZBPostQueueResponseEntry) + ntohl(pPostQueueAnswer->m_iNZBFilenameLen) + - ntohl(pPostQueueAnswer->m_iInfoNameLen) + ntohl(pPostQueueAnswer->m_iDestDirLen) + - ntohl(pPostQueueAnswer->m_iProgressLabelLen); + bufPtr += sizeof(SNZBPostQueueResponseEntry) + ntohl(postQueueAnswer->m_nzbFilenameLen) + + ntohl(postQueueAnswer->m_infoNameLen) + ntohl(postQueueAnswer->m_destDirLen) + + ntohl(postQueueAnswer->m_progressLabelLen); } - free(pBuf); + free(buf); printf("-----------------------------------\n"); } @@ -1088,38 +1088,38 @@ bool RemoteClient::RequestPostQueue() return true; } -bool RemoteClient::RequestWriteLog(int iKind, const char* szText) +bool RemoteClient::RequestWriteLog(int kind, const char* text) { if (!InitConnection()) return false; SNZBWriteLogRequest WriteLogRequest; - InitMessageBase(&WriteLogRequest.m_MessageBase, eRemoteRequestWriteLog, sizeof(WriteLogRequest)); - WriteLogRequest.m_iKind = htonl(iKind); - int iLength = strlen(szText) + 1; - WriteLogRequest.m_iTrailingDataLength = htonl(iLength); + InitMessageBase(&WriteLogRequest.m_messageBase, remoteRequestWriteLog, sizeof(WriteLogRequest)); + WriteLogRequest.m_kind = htonl(kind); + int length = strlen(text) + 1; + WriteLogRequest.m_trailingDataLength = htonl(length); - if (!m_pConnection->Send((char*)(&WriteLogRequest), sizeof(WriteLogRequest))) + if (!m_connection->Send((char*)(&WriteLogRequest), sizeof(WriteLogRequest))) { perror("m_pConnection->Send"); return false; } - m_pConnection->Send(szText, iLength); + m_connection->Send(text, length); bool OK = ReceiveBoolResponse(); - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } -bool RemoteClient::RequestScan(bool bSyncMode) +bool RemoteClient::RequestScan(bool syncMode) { if (!InitConnection()) return false; SNZBScanRequest ScanRequest; - InitMessageBase(&ScanRequest.m_MessageBase, eRemoteRequestScan, sizeof(ScanRequest)); + InitMessageBase(&ScanRequest.m_messageBase, remoteRequestScan, sizeof(ScanRequest)); - ScanRequest.m_bSyncMode = htonl(bSyncMode); + ScanRequest.m_syncMode = htonl(syncMode); - bool OK = m_pConnection->Send((char*)(&ScanRequest), sizeof(ScanRequest)); + bool OK = m_connection->Send((char*)(&ScanRequest), sizeof(ScanRequest)); if (OK) { OK = ReceiveBoolResponse(); @@ -1129,19 +1129,19 @@ bool RemoteClient::RequestScan(bool bSyncMode) perror("m_pConnection->Send"); } - m_pConnection->Disconnect(); + m_connection->Disconnect(); return OK; } -bool RemoteClient::RequestHistory(bool bWithHidden) +bool RemoteClient::RequestHistory(bool withHidden) { if (!InitConnection()) return false; SNZBHistoryRequest HistoryRequest; - InitMessageBase(&HistoryRequest.m_MessageBase, eRemoteRequestHistory, sizeof(HistoryRequest)); - HistoryRequest.m_bHidden = htonl(bWithHidden); + InitMessageBase(&HistoryRequest.m_messageBase, remoteRequestHistory, sizeof(HistoryRequest)); + HistoryRequest.m_hidden = htonl(withHidden); - if (!m_pConnection->Send((char*)(&HistoryRequest), sizeof(HistoryRequest))) + if (!m_connection->Send((char*)(&HistoryRequest), sizeof(HistoryRequest))) { perror("m_pConnection->Send"); return false; @@ -1151,29 +1151,29 @@ bool RemoteClient::RequestHistory(bool bWithHidden) // Now listen for the returned list SNZBHistoryResponse HistoryResponse; - bool bRead = m_pConnection->Recv((char*) &HistoryResponse, sizeof(HistoryResponse)); - if (!bRead || - (int)ntohl(HistoryResponse.m_MessageBase.m_iSignature) != (int)NZBMESSAGE_SIGNATURE || - ntohl(HistoryResponse.m_MessageBase.m_iStructSize) != sizeof(HistoryResponse)) + bool read = m_connection->Recv((char*) &HistoryResponse, sizeof(HistoryResponse)); + if (!read || + (int)ntohl(HistoryResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || + ntohl(HistoryResponse.m_messageBase.m_structSize) != sizeof(HistoryResponse)) { printf("No response or invalid response (timeout, not nzbget-server or wrong nzbget-server version)\n"); return false; } - char* pBuf = NULL; - if (ntohl(HistoryResponse.m_iTrailingDataLength) > 0) + char* buf = NULL; + if (ntohl(HistoryResponse.m_trailingDataLength) > 0) { - pBuf = (char*)malloc(ntohl(HistoryResponse.m_iTrailingDataLength)); - if (!m_pConnection->Recv(pBuf, ntohl(HistoryResponse.m_iTrailingDataLength))) + buf = (char*)malloc(ntohl(HistoryResponse.m_trailingDataLength)); + if (!m_connection->Recv(buf, ntohl(HistoryResponse.m_trailingDataLength))) { - free(pBuf); + free(buf); return false; } } - m_pConnection->Disconnect(); + m_connection->Disconnect(); - if (ntohl(HistoryResponse.m_iTrailingDataLength) == 0) + if (ntohl(HistoryResponse.m_trailingDataLength) == 0) { printf("Server has no files in history\n"); } @@ -1182,52 +1182,52 @@ bool RemoteClient::RequestHistory(bool bWithHidden) printf("History (most recent first)\n"); printf("-----------------------------------\n"); - char* pBufPtr = (char*)pBuf; - for (unsigned int i = 0; i < ntohl(HistoryResponse.m_iNrTrailingEntries); i++) + char* bufPtr = (char*)buf; + for (unsigned int i = 0; i < ntohl(HistoryResponse.m_nrTrailingEntries); i++) { - SNZBHistoryResponseEntry* pListAnswer = (SNZBHistoryResponseEntry*) pBufPtr; + SNZBHistoryResponseEntry* listAnswer = (SNZBHistoryResponseEntry*) bufPtr; - HistoryInfo::EKind eKind = (HistoryInfo::EKind)ntohl(pListAnswer->m_iKind); - const char* szNicename = pBufPtr + sizeof(SNZBHistoryResponseEntry); + HistoryInfo::EKind kind = (HistoryInfo::EKind)ntohl(listAnswer->m_kind); + const char* nicename = bufPtr + sizeof(SNZBHistoryResponseEntry); - if (eKind == HistoryInfo::hkNzb || eKind == HistoryInfo::hkDup) + if (kind == HistoryInfo::hkNzb || kind == HistoryInfo::hkDup) { - char szFiles[20]; - snprintf(szFiles, sizeof(szFiles), "%i files, ", ntohl(pListAnswer->m_iFileCount)); - szFiles[20 - 1] = '\0'; + char files[20]; + snprintf(files, sizeof(files), "%i files, ", ntohl(listAnswer->m_fileCount)); + files[20 - 1] = '\0'; - long long lSize = Util::JoinInt64(ntohl(pListAnswer->m_iSizeHi), ntohl(pListAnswer->m_iSizeLo)); + long long size = Util::JoinInt64(ntohl(listAnswer->m_sizeHi), ntohl(listAnswer->m_sizeLo)); - char szSize[20]; - Util::FormatSize(szSize, sizeof(szSize), lSize); + char sizeStr[20]; + Util::FormatSize(sizeStr, sizeof(sizeStr), size); - const char* szParStatusText[] = { "", "", ", Par failed", ", Par successful", ", Repair possible", ", Repair needed" }; - const char* szScriptStatusText[] = { "", ", Script status unknown", ", Script failed", ", Script successful" }; - int iParStatus = ntohl(pListAnswer->m_iParStatus); - int iScriptStatus = ntohl(pListAnswer->m_iScriptStatus); + const char* parStatusText[] = { "", "", ", Par failed", ", Par successful", ", Repair possible", ", Repair needed" }; + const char* scriptStatusText[] = { "", ", Script status unknown", ", Script failed", ", Script successful" }; + int parStatus = ntohl(listAnswer->m_parStatus); + int scriptStatus = ntohl(listAnswer->m_scriptStatus); - printf("[%i] %s (%s%s%s%s%s)\n", ntohl(pListAnswer->m_iID), szNicename, - (eKind == HistoryInfo::hkDup ? "Hidden, " : ""), - (eKind == HistoryInfo::hkDup ? "" : szFiles), szSize, - (eKind == HistoryInfo::hkDup ? "" : szParStatusText[iParStatus]), - (eKind == HistoryInfo::hkDup ? "" : szScriptStatusText[iScriptStatus])); + printf("[%i] %s (%s%s%s%s%s)\n", ntohl(listAnswer->m_id), nicename, + (kind == HistoryInfo::hkDup ? "Hidden, " : ""), + (kind == HistoryInfo::hkDup ? "" : files), sizeStr, + (kind == HistoryInfo::hkDup ? "" : parStatusText[parStatus]), + (kind == HistoryInfo::hkDup ? "" : scriptStatusText[scriptStatus])); } - else if (eKind == HistoryInfo::hkUrl) + else if (kind == HistoryInfo::hkUrl) { - const char* szUrlStatusText[] = { "", "", "Url download successful", "Url download failed", "", "Nzb scan skipped", "Nzb scan failed" }; + const char* urlStatusText[] = { "", "", "Url download successful", "Url download failed", "", "Nzb scan skipped", "Nzb scan failed" }; - printf("[%i] %s (URL, %s)\n", ntohl(pListAnswer->m_iID), szNicename, - szUrlStatusText[ntohl(pListAnswer->m_iUrlStatus)]); + printf("[%i] %s (URL, %s)\n", ntohl(listAnswer->m_id), nicename, + urlStatusText[ntohl(listAnswer->m_urlStatus)]); } - pBufPtr += sizeof(SNZBHistoryResponseEntry) + ntohl(pListAnswer->m_iNicenameLen); + bufPtr += sizeof(SNZBHistoryResponseEntry) + ntohl(listAnswer->m_nicenameLen); } printf("-----------------------------------\n"); - printf("Items: %i\n", ntohl(HistoryResponse.m_iNrTrailingEntries)); + printf("Items: %i\n", ntohl(HistoryResponse.m_nrTrailingEntries)); } - free(pBuf); + free(buf); return true; } diff --git a/daemon/remote/RemoteClient.h b/daemon/remote/RemoteClient.h index cffe4061..4077d3a6 100644 --- a/daemon/remote/RemoteClient.h +++ b/daemon/remote/RemoteClient.h @@ -38,20 +38,20 @@ private: class MatchedNZBInfo: public NZBInfo { public: - bool m_bMatch; + bool m_match; }; class MatchedFileInfo: public FileInfo { public: - bool m_bMatch; + bool m_match; }; - Connection* m_pConnection; - bool m_bVerbose; + Connection* m_connection; + bool m_verbose; bool InitConnection(); - void InitMessageBase(SNZBRequestBase* pMessageBase, int iRequest, int iSize); + void InitMessageBase(SNZBRequestBase* messageBase, int request, int size); bool ReceiveBoolResponse(); void printf(const char* msg, ...); void perror(const char* msg); @@ -59,25 +59,25 @@ private: public: RemoteClient(); ~RemoteClient(); - void SetVerbose(bool bVerbose) { m_bVerbose = bVerbose; }; - bool RequestServerDownload(const char* szNZBFilename, const char* szNZBContent, const char* szCategory, - bool bAddFirst, bool bAddPaused, int iPriority, - const char* szDupeKey, int iDupeMode, int iDupeScore); - bool RequestServerList(bool bFiles, bool bGroups, const char* szPattern); - bool RequestServerPauseUnpause(bool bPause, eRemotePauseUnpauseAction iAction); - bool RequestServerSetDownloadRate(int iRate); + void SetVerbose(bool verbose) { m_verbose = verbose; }; + bool RequestServerDownload(const char* nzbFilename, const char* nzbContent, const char* category, + bool addFirst, bool addPaused, int priority, + const char* dupeKey, int dupeMode, int dupeScore); + bool RequestServerList(bool files, bool groups, const char* pattern); + bool RequestServerPauseUnpause(bool pause, remotePauseUnpauseAction action); + bool RequestServerSetDownloadRate(int rate); bool RequestServerDumpDebug(); - bool RequestServerEditQueue(DownloadQueue::EEditAction eAction, int iOffset, const char* szText, - int* pIDList, int iIDCount, NameList* pNameList, eRemoteMatchMode iMatchMode); - bool RequestServerLog(int iLines); + bool RequestServerEditQueue(DownloadQueue::EEditAction action, int offset, const char* text, + int* idList, int idCount, NameList* nameList, remoteMatchMode matchMode); + bool RequestServerLog(int lines); bool RequestServerShutdown(); bool RequestServerReload(); bool RequestServerVersion(); bool RequestPostQueue(); - bool RequestWriteLog(int iKind, const char* szText); - bool RequestScan(bool bSyncMode); - bool RequestHistory(bool bWithHidden); - void BuildFileList(SNZBListResponse* pListResponse, const char* pTrailingData, DownloadQueue* pDownloadQueue); + bool RequestWriteLog(int kind, const char* text); + bool RequestScan(bool syncMode); + bool RequestHistory(bool withHidden); + void BuildFileList(SNZBListResponse* listResponse, const char* trailingData, DownloadQueue* downloadQueue); }; #endif diff --git a/daemon/remote/RemoteServer.cpp b/daemon/remote/RemoteServer.cpp index 1939c2a0..e41dcb79 100644 --- a/daemon/remote/RemoteServer.cpp +++ b/daemon/remote/RemoteServer.cpp @@ -53,19 +53,19 @@ //***************************************************************** // RemoteServer -RemoteServer::RemoteServer(bool bTLS) +RemoteServer::RemoteServer(bool tLS) { debug("Creating RemoteServer"); - m_bTLS = bTLS; - m_pConnection = NULL; + m_tLS = tLS; + m_connection = NULL; } RemoteServer::~RemoteServer() { debug("Destroying RemoteServer"); - delete m_pConnection; + delete m_connection; } void RemoteServer::Run() @@ -73,7 +73,7 @@ void RemoteServer::Run() debug("Entering RemoteServer-loop"); #ifndef DISABLE_TLS - if (m_bTLS) + if (m_tLS) { if (strlen(g_pOptions->GetSecureCert()) == 0 || !Util::FileExists(g_pOptions->GetSecureCert())) { @@ -91,25 +91,25 @@ void RemoteServer::Run() while (!IsStopped()) { - bool bBind = true; + bool bind = true; - if (!m_pConnection) + if (!m_connection) { - m_pConnection = new Connection(g_pOptions->GetControlIP(), - m_bTLS ? g_pOptions->GetSecurePort() : g_pOptions->GetControlPort(), - m_bTLS); - m_pConnection->SetTimeout(g_pOptions->GetUrlTimeout()); - m_pConnection->SetSuppressErrors(false); - bBind = m_pConnection->Bind(); + m_connection = new Connection(g_pOptions->GetControlIP(), + m_tLS ? g_pOptions->GetSecurePort() : g_pOptions->GetControlPort(), + m_tLS); + m_connection->SetTimeout(g_pOptions->GetUrlTimeout()); + m_connection->SetSuppressErrors(false); + bind = m_connection->Bind(); } // Accept connections and store the new Connection - Connection* pAcceptedConnection = NULL; - if (bBind) + Connection* acceptedConnection = NULL; + if (bind) { - pAcceptedConnection = m_pConnection->Accept(); + acceptedConnection = m_connection->Accept(); } - if (!bBind || pAcceptedConnection == NULL) + if (!bind || acceptedConnection == NULL) { // Remote server could not bind or accept connection, waiting 1/2 sec and try again if (IsStopped()) @@ -117,23 +117,23 @@ void RemoteServer::Run() break; } usleep(500 * 1000); - delete m_pConnection; - m_pConnection = NULL; + delete m_connection; + m_connection = NULL; continue; } RequestProcessor* commandThread = new RequestProcessor(); commandThread->SetAutoDestroy(true); - commandThread->SetConnection(pAcceptedConnection); + commandThread->SetConnection(acceptedConnection); #ifndef DISABLE_TLS - commandThread->SetTLS(m_bTLS); + commandThread->SetTLS(m_tLS); #endif commandThread->Start(); } - if (m_pConnection) + if (m_connection) { - m_pConnection->Disconnect(); + m_connection->Disconnect(); } debug("Exiting RemoteServer-loop"); @@ -142,12 +142,12 @@ void RemoteServer::Run() void RemoteServer::Stop() { Thread::Stop(); - if (m_pConnection) + if (m_connection) { - m_pConnection->SetSuppressErrors(true); - m_pConnection->Cancel(); + m_connection->SetSuppressErrors(true); + m_connection->Cancel(); #ifdef WIN32 - m_pConnection->Disconnect(); + m_connection->Disconnect(); #endif } } @@ -157,18 +157,18 @@ void RemoteServer::Stop() RequestProcessor::~RequestProcessor() { - m_pConnection->Disconnect(); - delete m_pConnection; + m_connection->Disconnect(); + delete m_connection; } void RequestProcessor::Run() { - bool bOK = false; + bool ok = false; - m_pConnection->SetSuppressErrors(true); + m_connection->SetSuppressErrors(true); #ifndef DISABLE_TLS - if (m_bTLS && !m_pConnection->StartTLS(false, g_pOptions->GetSecureCert(), g_pOptions->GetSecureKey())) + if (m_tLS && !m_connection->StartTLS(false, g_pOptions->GetSecureCert(), g_pOptions->GetSecureKey())) { debug("Could not establish secure connection to web-client: Start TLS failed"); return; @@ -176,63 +176,63 @@ void RequestProcessor::Run() #endif // Read the first 4 bytes to determine request type - int iSignature = 0; - if (!m_pConnection->Recv((char*)&iSignature, 4)) + int signature = 0; + if (!m_connection->Recv((char*)&signature, 4)) { debug("Could not read request signature"); return; } - if ((int)ntohl(iSignature) == (int)NZBMESSAGE_SIGNATURE) + if ((int)ntohl(signature) == (int)NZBMESSAGE_SIGNATURE) { // binary request received - bOK = true; + ok = true; BinRpcProcessor processor; - processor.SetConnection(m_pConnection); + processor.SetConnection(m_connection); processor.Execute(); } - else if (!strncmp((char*)&iSignature, "POST", 4) || - !strncmp((char*)&iSignature, "GET ", 4) || - !strncmp((char*)&iSignature, "OPTI", 4)) + else if (!strncmp((char*)&signature, "POST", 4) || + !strncmp((char*)&signature, "GET ", 4) || + !strncmp((char*)&signature, "OPTI", 4)) { // HTTP request received - char szBuffer[1024]; - if (m_pConnection->ReadLine(szBuffer, sizeof(szBuffer), NULL)) + char buffer[1024]; + if (m_connection->ReadLine(buffer, sizeof(buffer), NULL)) { - WebProcessor::EHttpMethod eHttpMethod = WebProcessor::hmGet; - char* szUrl = szBuffer; - if (!strncmp((char*)&iSignature, "POST", 4)) + WebProcessor::EHttpMethod httpMethod = WebProcessor::hmGet; + char* url = buffer; + if (!strncmp((char*)&signature, "POST", 4)) { - eHttpMethod = WebProcessor::hmPost; - szUrl++; + httpMethod = WebProcessor::hmPost; + url++; } - if (!strncmp((char*)&iSignature, "OPTI", 4) && strlen(szUrl) > 4) + if (!strncmp((char*)&signature, "OPTI", 4) && strlen(url) > 4) { - eHttpMethod = WebProcessor::hmOptions; - szUrl += 4; + httpMethod = WebProcessor::hmOptions; + url += 4; } - if (char* p = strchr(szUrl, ' ')) + if (char* p = strchr(url, ' ')) { *p = '\0'; } - debug("url: %s", szUrl); + debug("url: %s", url); WebProcessor processor; - processor.SetConnection(m_pConnection); - processor.SetUrl(szUrl); - processor.SetHttpMethod(eHttpMethod); + processor.SetConnection(m_connection); + processor.SetUrl(url); + processor.SetHttpMethod(httpMethod); processor.Execute(); - m_pConnection->SetGracefull(true); - m_pConnection->Disconnect(); + m_connection->SetGracefull(true); + m_connection->Disconnect(); - bOK = true; + ok = true; } } - if (!bOK) + if (!ok) { - warn("Non-nzbget request received on port %i from %s", m_bTLS ? g_pOptions->GetSecurePort() : g_pOptions->GetControlPort(), m_pConnection->GetRemoteAddr()); + warn("Non-nzbget request received on port %i from %s", m_tLS ? g_pOptions->GetSecurePort() : g_pOptions->GetControlPort(), m_connection->GetRemoteAddr()); } } diff --git a/daemon/remote/RemoteServer.h b/daemon/remote/RemoteServer.h index 26e4bb3e..83ba7648 100644 --- a/daemon/remote/RemoteServer.h +++ b/daemon/remote/RemoteServer.h @@ -33,11 +33,11 @@ class RemoteServer : public Thread { private: - bool m_bTLS; - Connection* m_pConnection; + bool m_tLS; + Connection* m_connection; public: - RemoteServer(bool bTLS); + RemoteServer(bool tLS); ~RemoteServer(); virtual void Run(); virtual void Stop(); @@ -46,14 +46,14 @@ public: class RequestProcessor : public Thread { private: - bool m_bTLS; - Connection* m_pConnection; + bool m_tLS; + Connection* m_connection; public: ~RequestProcessor(); virtual void Run(); - void SetTLS(bool bTLS) { m_bTLS = bTLS; } - void SetConnection(Connection* pConnection) { m_pConnection = pConnection; } + void SetTLS(bool tLS) { m_tLS = tLS; } + void SetConnection(Connection* connection) { m_connection = connection; } }; #endif diff --git a/daemon/remote/WebServer.cpp b/daemon/remote/WebServer.cpp index 23353ead..e3f6a433 100644 --- a/daemon/remote/WebServer.cpp +++ b/daemon/remote/WebServer.cpp @@ -50,14 +50,14 @@ static const char* ERR_HTTP_NOT_FOUND = "404 Not Found"; static const char* ERR_HTTP_SERVICE_UNAVAILABLE = "503 Service Unavailable"; static const int MAX_UNCOMPRESSED_SIZE = 500; -char WebProcessor::m_szServerAuthToken[3][49]; +char WebProcessor::m_serverAuthToken[3][49]; //***************************************************************** // WebProcessor void WebProcessor::Init() { - if (m_szServerAuthToken[0][0] != 0) + if (m_serverAuthToken[0][0] != 0) { // already initialized return; @@ -65,63 +65,63 @@ void WebProcessor::Init() for (int j = uaControl; j <= uaAdd; j++) { - for (int i = 0; i < sizeof(m_szServerAuthToken[j]) - 1; i++) + for (int i = 0; i < sizeof(m_serverAuthToken[j]) - 1; i++) { int ch = rand() % (10 + 26 + 26); if (0 <= ch && ch < 10) { - m_szServerAuthToken[j][i] = '0' + ch; + m_serverAuthToken[j][i] = '0' + ch; } else if (10 <= ch && ch < 10 + 26) { - m_szServerAuthToken[j][i] = 'a' + ch - 10; + m_serverAuthToken[j][i] = 'a' + ch - 10; } else { - m_szServerAuthToken[j][i] = 'A' + ch - 10 - 26; + m_serverAuthToken[j][i] = 'A' + ch - 10 - 26; } } - m_szServerAuthToken[j][sizeof(m_szServerAuthToken[j]) - 1] = '\0'; - debug("X-Auth-Token[%i]: %s", j, m_szServerAuthToken[j]); + m_serverAuthToken[j][sizeof(m_serverAuthToken[j]) - 1] = '\0'; + debug("X-Auth-Token[%i]: %s", j, m_serverAuthToken[j]); } } WebProcessor::WebProcessor() { - m_pConnection = NULL; - m_szRequest = NULL; - m_szUrl = NULL; - m_szOrigin = NULL; + m_connection = NULL; + m_request = NULL; + m_url = NULL; + m_origin = NULL; } WebProcessor::~WebProcessor() { - free(m_szRequest); - free(m_szUrl); - free(m_szOrigin); + free(m_request); + free(m_url); + free(m_origin); } -void WebProcessor::SetUrl(const char* szUrl) +void WebProcessor::SetUrl(const char* url) { - m_szUrl = strdup(szUrl); + m_url = strdup(url); } void WebProcessor::Execute() { - m_bGZip =false; - m_eUserAccess = uaControl; - m_szAuthInfo[0] = '\0'; - m_szAuthToken[0] = '\0'; + m_gZip =false; + m_userAccess = uaControl; + m_authInfo[0] = '\0'; + m_authToken[0] = '\0'; ParseHeaders(); - if (m_eHttpMethod == hmPost && m_iContentLen <= 0) + if (m_httpMethod == hmPost && m_contentLen <= 0) { error("Invalid-request: content length is 0"); return; } - if (m_eHttpMethod == hmOptions) + if (m_httpMethod == hmOptions) { SendOptionsResponse(); return; @@ -135,21 +135,21 @@ void WebProcessor::Execute() return; } - if (m_eHttpMethod == hmPost) + if (m_httpMethod == hmPost) { // reading http body (request content) - m_szRequest = (char*)malloc(m_iContentLen + 1); - m_szRequest[m_iContentLen] = '\0'; + m_request = (char*)malloc(m_contentLen + 1); + m_request[m_contentLen] = '\0'; - if (!m_pConnection->Recv(m_szRequest, m_iContentLen)) + if (!m_connection->Recv(m_request, m_contentLen)) { error("Invalid-request: could not read data"); return; } - debug("Request=%s", m_szRequest); + debug("Request=%s", m_request); } - debug("request received from %s", m_pConnection->GetRemoteAddr()); + debug("request received from %s", m_connection->GetRemoteAddr()); Dispatch(); } @@ -157,38 +157,38 @@ void WebProcessor::Execute() void WebProcessor::ParseHeaders() { // reading http header - char szBuffer[1024]; - m_iContentLen = 0; - while (char* p = m_pConnection->ReadLine(szBuffer, sizeof(szBuffer), NULL)) + char buffer[1024]; + m_contentLen = 0; + while (char* p = m_connection->ReadLine(buffer, sizeof(buffer), NULL)) { if (char* pe = strrchr(p, '\r')) *pe = '\0'; debug("header=%s", p); if (!strncasecmp(p, "Content-Length: ", 16)) { - m_iContentLen = atoi(p + 16); + m_contentLen = atoi(p + 16); } if (!strncasecmp(p, "Authorization: Basic ", 21)) { - char* szAuthInfo64 = p + 21; - if (strlen(szAuthInfo64) > sizeof(m_szAuthInfo)) + char* authInfo64 = p + 21; + if (strlen(authInfo64) > sizeof(m_authInfo)) { error("Invalid-request: auth-info too big"); return; } - m_szAuthInfo[WebUtil::DecodeBase64(szAuthInfo64, 0, m_szAuthInfo)] = '\0'; + m_authInfo[WebUtil::DecodeBase64(authInfo64, 0, m_authInfo)] = '\0'; } if (!strncasecmp(p, "Accept-Encoding: ", 17)) { - m_bGZip = strstr(p, "gzip"); + m_gZip = strstr(p, "gzip"); } if (!strncasecmp(p, "Origin: ", 8)) { - m_szOrigin = strdup(p + 8); + m_origin = strdup(p + 8); } if (!strncasecmp(p, "X-Auth-Token: ", 14)) { - strncpy(m_szAuthToken, p + 14, sizeof(m_szAuthToken)-1); - m_szAuthToken[sizeof(m_szAuthToken)-1] = '\0'; + strncpy(m_authToken, p + 14, sizeof(m_authToken)-1); + m_authToken[sizeof(m_authToken)-1] = '\0'; } if (*p == '\0') { @@ -196,71 +196,71 @@ void WebProcessor::ParseHeaders() } } - debug("URL=%s", m_szUrl); - debug("Authorization=%s", m_szAuthInfo); - debug("X-Auth-Token=%s", m_szAuthToken); + debug("URL=%s", m_url); + debug("Authorization=%s", m_authInfo); + debug("X-Auth-Token=%s", m_authToken); } void WebProcessor::ParseURL() { // remove subfolder "nzbget" from the path (if exists) // http://localhost:6789/nzbget/username:password/jsonrpc -> http://localhost:6789/username:password/jsonrpc - if (!strncmp(m_szUrl, "/nzbget/", 8)) + if (!strncmp(m_url, "/nzbget/", 8)) { - char* sz_OldUrl = m_szUrl; - m_szUrl = strdup(m_szUrl + 7); - free(sz_OldUrl); + char* _OldUrl = m_url; + m_url = strdup(m_url + 7); + free(_OldUrl); } // http://localhost:6789/nzbget -> http://localhost:6789 - if (!strcmp(m_szUrl, "/nzbget")) + if (!strcmp(m_url, "/nzbget")) { - char szRedirectURL[1024]; - snprintf(szRedirectURL, 1024, "%s/", m_szUrl); - szRedirectURL[1024-1] = '\0'; - SendRedirectResponse(szRedirectURL); + char redirectUrl[1024]; + snprintf(redirectUrl, 1024, "%s/", m_url); + redirectUrl[1024-1] = '\0'; + SendRedirectResponse(redirectUrl); return; } // authorization via URL in format: // http://localhost:6789/username:password/jsonrpc - char* pauth1 = strchr(m_szUrl + 1, ':'); - char* pauth2 = strchr(m_szUrl + 1, '/'); + char* pauth1 = strchr(m_url + 1, ':'); + char* pauth2 = strchr(m_url + 1, '/'); if (pauth1 && pauth1 < pauth2) { - char* pstart = m_szUrl + 1; - int iLen = 0; + char* pstart = m_url + 1; + int len = 0; char* pend = strchr(pstart + 1, '/'); if (pend) { - iLen = (int)(pend - pstart < (int)sizeof(m_szAuthInfo) - 1 ? pend - pstart : (int)sizeof(m_szAuthInfo) - 1); + len = (int)(pend - pstart < (int)sizeof(m_authInfo) - 1 ? pend - pstart : (int)sizeof(m_authInfo) - 1); } else { - iLen = strlen(pstart); + len = strlen(pstart); } - strncpy(m_szAuthInfo, pstart, iLen); - m_szAuthInfo[iLen] = '\0'; - char* sz_OldUrl = m_szUrl; - m_szUrl = strdup(pend); - free(sz_OldUrl); + strncpy(m_authInfo, pstart, len); + m_authInfo[len] = '\0'; + char* _OldUrl = m_url; + m_url = strdup(pend); + free(_OldUrl); } - debug("Final URL=%s", m_szUrl); + debug("Final URL=%s", m_url); } bool WebProcessor::CheckCredentials() { if (!Util::EmptyStr(g_pOptions->GetControlPassword()) && - !(!Util::EmptyStr(g_pOptions->GetAuthorizedIP()) && IsAuthorizedIP(m_pConnection->GetRemoteAddr()))) + !(!Util::EmptyStr(g_pOptions->GetAuthorizedIP()) && IsAuthorizedIP(m_connection->GetRemoteAddr()))) { - if (Util::EmptyStr(m_szAuthInfo)) + if (Util::EmptyStr(m_authInfo)) { // Authorization via X-Auth-Token for (int j = uaControl; j <= uaAdd; j++) { - if (!strcmp(m_szAuthToken, m_szServerAuthToken[j])) + if (!strcmp(m_authToken, m_serverAuthToken[j])) { - m_eUserAccess = (EUserAccess)j; + m_userAccess = (EUserAccess)j; return true; } } @@ -268,31 +268,31 @@ bool WebProcessor::CheckCredentials() } // Authorization via username:password - char* pw = strchr(m_szAuthInfo, ':'); + char* pw = strchr(m_authInfo, ':'); if (pw) *pw++ = '\0'; if ((Util::EmptyStr(g_pOptions->GetControlUsername()) || - !strcmp(m_szAuthInfo, g_pOptions->GetControlUsername())) && + !strcmp(m_authInfo, g_pOptions->GetControlUsername())) && pw && !strcmp(pw, g_pOptions->GetControlPassword())) { - m_eUserAccess = uaControl; + m_userAccess = uaControl; } else if (!Util::EmptyStr(g_pOptions->GetRestrictedUsername()) && - !strcmp(m_szAuthInfo, g_pOptions->GetRestrictedUsername()) && + !strcmp(m_authInfo, g_pOptions->GetRestrictedUsername()) && pw && !strcmp(pw, g_pOptions->GetRestrictedPassword())) { - m_eUserAccess = uaRestricted; + m_userAccess = uaRestricted; } else if (!Util::EmptyStr(g_pOptions->GetAddUsername()) && - !strcmp(m_szAuthInfo, g_pOptions->GetAddUsername()) && + !strcmp(m_authInfo, g_pOptions->GetAddUsername()) && pw && !strcmp(pw, g_pOptions->GetAddPassword())) { - m_eUserAccess = uaAdd; + m_userAccess = uaAdd; } else { warn("Request received on port %i from %s, but username or password invalid (%s:%s)", - g_pOptions->GetControlPort(), m_pConnection->GetRemoteAddr(), m_szAuthInfo, pw); + g_pOptions->GetControlPort(), m_connection->GetRemoteAddr(), m_authInfo, pw); return false; } } @@ -300,40 +300,40 @@ bool WebProcessor::CheckCredentials() return true; } -bool WebProcessor::IsAuthorizedIP(const char* szRemoteAddr) +bool WebProcessor::IsAuthorizedIP(const char* remoteAddr) { - const char* szRemoteIP = m_pConnection->GetRemoteAddr(); + const char* remoteIP = m_connection->GetRemoteAddr(); // split option AuthorizedIP into tokens and check each token - bool bAuthorized = false; + bool authorized = false; Tokenizer tok(g_pOptions->GetAuthorizedIP(), ",;"); - while (const char* szIP = tok.Next()) + while (const char* iP = tok.Next()) { - if (!strcmp(szIP, szRemoteIP)) + if (!strcmp(iP, remoteIP)) { - bAuthorized = true; + authorized = true; break; } } - return bAuthorized; + return authorized; } void WebProcessor::Dispatch() { - if (*m_szUrl != '/') + if (*m_url != '/') { SendErrorResponse(ERR_HTTP_BAD_REQUEST); return; } - if (XmlRpcProcessor::IsRpcRequest(m_szUrl)) + if (XmlRpcProcessor::IsRpcRequest(m_url)) { XmlRpcProcessor processor; - processor.SetRequest(m_szRequest); - processor.SetHttpMethod(m_eHttpMethod == hmGet ? XmlRpcProcessor::hmGet : XmlRpcProcessor::hmPost); - processor.SetUserAccess((XmlRpcProcessor::EUserAccess)m_eUserAccess); - processor.SetUrl(m_szUrl); + processor.SetRequest(m_request); + processor.SetHttpMethod(m_httpMethod == hmGet ? XmlRpcProcessor::hmGet : XmlRpcProcessor::hmPost); + processor.SetUserAccess((XmlRpcProcessor::EUserAccess)m_userAccess); + processor.SetUrl(m_url); processor.Execute(); SendBodyResponse(processor.GetResponse(), strlen(processor.GetResponse()), processor.GetContentType()); return; @@ -345,7 +345,7 @@ void WebProcessor::Dispatch() return; } - if (m_eHttpMethod != hmGet) + if (m_httpMethod != hmGet) { SendErrorResponse(ERR_HTTP_BAD_REQUEST); return; @@ -353,7 +353,7 @@ void WebProcessor::Dispatch() // for security reasons we allow only characters "0..9 A..Z a..z . - _ /" in the URLs // we also don't allow ".." in the URLs - for (char *p = m_szUrl; *p; p++) + for (char *p = m_url; *p; p++) { if (!((*p >= '0' && *p <= '9') || (*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || *p == '.' || *p == '-' || *p == '_' || *p == '/') || (*p == '.' && p[1] == '.')) @@ -363,15 +363,15 @@ void WebProcessor::Dispatch() } } - const char *szDefRes = ""; - if (m_szUrl[strlen(m_szUrl)-1] == '/') + const char *defRes = ""; + if (m_url[strlen(m_url)-1] == '/') { // default file in directory (if not specified) is "index.html" - szDefRes = "index.html"; + defRes = "index.html"; } char disk_filename[1024]; - snprintf(disk_filename, sizeof(disk_filename), "%s%s%s", g_pOptions->GetWebDir(), m_szUrl + 1, szDefRes); + snprintf(disk_filename, sizeof(disk_filename), "%s%s%s", g_pOptions->GetWebDir(), m_url + 1, defRes); disk_filename[sizeof(disk_filename)-1] = '\0'; @@ -387,12 +387,12 @@ void WebProcessor::SendAuthResponse() "Content-Type: text/plain\r\n" "Server: nzbget-%s\r\n" "\r\n"; - char szResponseHeader[1024]; - snprintf(szResponseHeader, 1024, AUTH_RESPONSE_HEADER, Util::VersionRevision()); + char responseHeader[1024]; + snprintf(responseHeader, 1024, AUTH_RESPONSE_HEADER, Util::VersionRevision()); // Send the response answer - debug("ResponseHeader=%s", szResponseHeader); - m_pConnection->Send(szResponseHeader, strlen(szResponseHeader)); + debug("ResponseHeader=%s", responseHeader); + m_connection->Send(responseHeader, strlen(responseHeader)); } void WebProcessor::SendOptionsResponse() @@ -408,17 +408,17 @@ void WebProcessor::SendOptionsResponse() "Access-Control-Allow-Headers: Content-Type, Authorization\r\n" "Server: nzbget-%s\r\n" "\r\n"; - char szResponseHeader[1024]; - snprintf(szResponseHeader, 1024, OPTIONS_RESPONSE_HEADER, - m_szOrigin ? m_szOrigin : "", + char responseHeader[1024]; + snprintf(responseHeader, 1024, OPTIONS_RESPONSE_HEADER, + m_origin ? m_origin : "", Util::VersionRevision()); // Send the response answer - debug("ResponseHeader=%s", szResponseHeader); - m_pConnection->Send(szResponseHeader, strlen(szResponseHeader)); + debug("ResponseHeader=%s", responseHeader); + m_connection->Send(responseHeader, strlen(responseHeader)); } -void WebProcessor::SendErrorResponse(const char* szErrCode) +void WebProcessor::SendErrorResponse(const char* errCode) { const char* RESPONSE_HEADER = "HTTP/1.0 %s\r\n" @@ -428,21 +428,21 @@ void WebProcessor::SendErrorResponse(const char* szErrCode) "Server: nzbget-%s\r\n" "\r\n"; - warn("Web-Server: %s, Resource: %s", szErrCode, m_szUrl); + warn("Web-Server: %s, Resource: %s", errCode, m_url); - char szResponseBody[1024]; - snprintf(szResponseBody, 1024, "%sError: %s", szErrCode, szErrCode); - int iPageContentLen = strlen(szResponseBody); + char responseBody[1024]; + snprintf(responseBody, 1024, "%sError: %s", errCode, errCode); + int pageContentLen = strlen(responseBody); - char szResponseHeader[1024]; - snprintf(szResponseHeader, 1024, RESPONSE_HEADER, szErrCode, iPageContentLen, Util::VersionRevision()); + char responseHeader[1024]; + snprintf(responseHeader, 1024, RESPONSE_HEADER, errCode, pageContentLen, Util::VersionRevision()); // Send the response answer - m_pConnection->Send(szResponseHeader, strlen(szResponseHeader)); - m_pConnection->Send(szResponseBody, iPageContentLen); + m_connection->Send(responseHeader, strlen(responseHeader)); + m_connection->Send(responseBody, pageContentLen); } -void WebProcessor::SendRedirectResponse(const char* szURL) +void WebProcessor::SendRedirectResponse(const char* url) { const char* REDIRECT_RESPONSE_HEADER = "HTTP/1.0 301 Moved Permanently\r\n" @@ -450,15 +450,15 @@ void WebProcessor::SendRedirectResponse(const char* szURL) "Connection: close\r\n" "Server: nzbget-%s\r\n" "\r\n"; - char szResponseHeader[1024]; - snprintf(szResponseHeader, 1024, REDIRECT_RESPONSE_HEADER, szURL, Util::VersionRevision()); + char responseHeader[1024]; + snprintf(responseHeader, 1024, REDIRECT_RESPONSE_HEADER, url, Util::VersionRevision()); // Send the response answer - debug("ResponseHeader=%s", szResponseHeader); - m_pConnection->Send(szResponseHeader, strlen(szResponseHeader)); + debug("ResponseHeader=%s", responseHeader); + m_connection->Send(responseHeader, strlen(responseHeader)); } -void WebProcessor::SendBodyResponse(const char* szBody, int iBodyLen, const char* szContentType) +void WebProcessor::SendBodyResponse(const char* body, int bodyLen, const char* contentType) { const char* RESPONSE_HEADER = "HTTP/1.1 200 OK\r\n" @@ -476,100 +476,100 @@ void WebProcessor::SendBodyResponse(const char* szBody, int iBodyLen, const char "\r\n"; #ifndef DISABLE_GZIP - char *szGBuf = NULL; - bool bGZip = m_bGZip && iBodyLen > MAX_UNCOMPRESSED_SIZE; - if (bGZip) + char *gBuf = NULL; + bool gZip = m_gZip && bodyLen > MAX_UNCOMPRESSED_SIZE; + if (gZip) { - unsigned int iOutLen = ZLib::GZipLen(iBodyLen); - szGBuf = (char*)malloc(iOutLen); - int iGZippedLen = ZLib::GZip(szBody, iBodyLen, szGBuf, iOutLen); - if (iGZippedLen > 0 && iGZippedLen < iBodyLen) + unsigned int outLen = ZLib::GZipLen(bodyLen); + gBuf = (char*)malloc(outLen); + int gZippedLen = ZLib::GZip(body, bodyLen, gBuf, outLen); + if (gZippedLen > 0 && gZippedLen < bodyLen) { - szBody = szGBuf; - iBodyLen = iGZippedLen; + body = gBuf; + bodyLen = gZippedLen; } else { - free(szGBuf); - szGBuf = NULL; - bGZip = false; + free(gBuf); + gBuf = NULL; + gZip = false; } } #else - bool bGZip = false; + bool gZip = false; #endif - char szContentTypeHeader[1024]; - if (szContentType) + char contentTypeHeader[1024]; + if (contentType) { - snprintf(szContentTypeHeader, 1024, "Content-Type: %s\r\n", szContentType); + snprintf(contentTypeHeader, 1024, "Content-Type: %s\r\n", contentType); } else { - szContentTypeHeader[0] = '\0'; + contentTypeHeader[0] = '\0'; } - char szResponseHeader[1024]; - snprintf(szResponseHeader, 1024, RESPONSE_HEADER, - m_szOrigin ? m_szOrigin : "", - m_szServerAuthToken[m_eUserAccess], iBodyLen, szContentTypeHeader, - bGZip ? "Content-Encoding: gzip\r\n" : "", + char responseHeader[1024]; + snprintf(responseHeader, 1024, RESPONSE_HEADER, + m_origin ? m_origin : "", + m_serverAuthToken[m_userAccess], bodyLen, contentTypeHeader, + gZip ? "Content-Encoding: gzip\r\n" : "", Util::VersionRevision()); // Send the request answer - m_pConnection->Send(szResponseHeader, strlen(szResponseHeader)); - m_pConnection->Send(szBody, iBodyLen); + m_connection->Send(responseHeader, strlen(responseHeader)); + m_connection->Send(body, bodyLen); #ifndef DISABLE_GZIP - free(szGBuf); + free(gBuf); #endif } -void WebProcessor::SendFileResponse(const char* szFilename) +void WebProcessor::SendFileResponse(const char* filename) { - debug("serving file: %s", szFilename); + debug("serving file: %s", filename); - char *szBody; - int iBodyLen; - if (!Util::LoadFileIntoBuffer(szFilename, &szBody, &iBodyLen)) + char *body; + int bodyLen; + if (!Util::LoadFileIntoBuffer(filename, &body, &bodyLen)) { SendErrorResponse(ERR_HTTP_NOT_FOUND); return; } // "LoadFileIntoBuffer" adds a trailing NULL, which we don't need here - iBodyLen--; + bodyLen--; - SendBodyResponse(szBody, iBodyLen, DetectContentType(szFilename)); + SendBodyResponse(body, bodyLen, DetectContentType(filename)); - free(szBody); + free(body); } -const char* WebProcessor::DetectContentType(const char* szFilename) +const char* WebProcessor::DetectContentType(const char* filename) { - if (const char *szExt = strrchr(szFilename, '.')) + if (const char *ext = strrchr(filename, '.')) { - if (!strcasecmp(szExt, ".css")) + if (!strcasecmp(ext, ".css")) { return "text/css"; } - else if (!strcasecmp(szExt, ".html")) + else if (!strcasecmp(ext, ".html")) { return "text/html"; } - else if (!strcasecmp(szExt, ".js")) + else if (!strcasecmp(ext, ".js")) { return "application/javascript"; } - else if (!strcasecmp(szExt, ".png")) + else if (!strcasecmp(ext, ".png")) { return "image/png"; } - else if (!strcasecmp(szExt, ".jpeg")) + else if (!strcasecmp(ext, ".jpeg")) { return "image/jpeg"; } - else if (!strcasecmp(szExt, ".gif")) + else if (!strcasecmp(ext, ".gif")) { return "image/gif"; } diff --git a/daemon/remote/WebServer.h b/daemon/remote/WebServer.h index 0a8db04f..a9aafb25 100644 --- a/daemon/remote/WebServer.h +++ b/daemon/remote/WebServer.h @@ -46,27 +46,27 @@ public: }; private: - Connection* m_pConnection; - char* m_szRequest; - char* m_szUrl; - EHttpMethod m_eHttpMethod; - EUserAccess m_eUserAccess; - bool m_bGZip; - char* m_szOrigin; - int m_iContentLen; - char m_szAuthInfo[256+1]; - char m_szAuthToken[48+1]; - static char m_szServerAuthToken[3][48+1]; + Connection* m_connection; + char* m_request; + char* m_url; + EHttpMethod m_httpMethod; + EUserAccess m_userAccess; + bool m_gZip; + char* m_origin; + int m_contentLen; + char m_authInfo[256+1]; + char m_authToken[48+1]; + static char m_serverAuthToken[3][48+1]; void Dispatch(); void SendAuthResponse(); void SendOptionsResponse(); - void SendErrorResponse(const char* szErrCode); - void SendFileResponse(const char* szFilename); - void SendBodyResponse(const char* szBody, int iBodyLen, const char* szContentType); - void SendRedirectResponse(const char* szURL); - const char* DetectContentType(const char* szFilename); - bool IsAuthorizedIP(const char* szRemoteAddr); + void SendErrorResponse(const char* errCode); + void SendFileResponse(const char* filename); + void SendBodyResponse(const char* body, int bodyLen, const char* contentType); + void SendRedirectResponse(const char* url); + const char* DetectContentType(const char* filename); + bool IsAuthorizedIP(const char* remoteAddr); void ParseHeaders(); void ParseURL(); bool CheckCredentials(); @@ -76,9 +76,9 @@ public: ~WebProcessor(); static void Init(); void Execute(); - void SetConnection(Connection* pConnection) { m_pConnection = pConnection; } - void SetUrl(const char* szUrl); - void SetHttpMethod(EHttpMethod eHttpMethod) { m_eHttpMethod = eHttpMethod; } + void SetConnection(Connection* connection) { m_connection = connection; } + void SetUrl(const char* url); + void SetHttpMethod(EHttpMethod httpMethod) { m_httpMethod = httpMethod; } }; #endif diff --git a/daemon/remote/XmlRpc.cpp b/daemon/remote/XmlRpc.cpp index cba6e8ad..49cc6e79 100644 --- a/daemon/remote/XmlRpc.cpp +++ b/daemon/remote/XmlRpc.cpp @@ -60,11 +60,11 @@ extern void Reload(); class ErrorXmlCommand: public XmlCommand { private: - int m_iErrCode; - const char* m_szErrText; + int m_errCode; + const char* m_errText; public: - ErrorXmlCommand(int iErrCode, const char* szErrText); + ErrorXmlCommand(int errCode, const char* errText); virtual void Execute(); }; @@ -79,11 +79,11 @@ public: }; private: - bool m_bPause; - EPauseAction m_eEPauseAction; + bool m_pause; + EPauseAction m_ePauseAction; public: - PauseUnpauseXmlCommand(bool bPause, EPauseAction eEPauseAction); + PauseUnpauseXmlCommand(bool pause, EPauseAction ePauseAction); virtual void Execute(); }; @@ -132,8 +132,8 @@ public: class LogXmlCommand: public XmlCommand { protected: - int m_iIDFrom; - int m_iNrEntries; + int m_idFrom; + int m_nrEntries; virtual MessageList* LockMessages(); virtual void UnlockMessages(); public: @@ -143,8 +143,8 @@ public: class NzbInfoXmlCommand: public XmlCommand { protected: - void AppendNZBInfoFields(NZBInfo* pNZBInfo); - void AppendPostInfoFields(PostInfo* pPostInfo, int iLogEntries, bool bPostQueue); + void AppendNZBInfoFields(NZBInfo* nzbInfo); + void AppendPostInfoFields(PostInfo* postInfo, int logEntries, bool postQueue); }; class ListFilesXmlCommand: public XmlCommand @@ -156,7 +156,7 @@ public: class ListGroupsXmlCommand: public NzbInfoXmlCommand { private: - const char* DetectStatus(NZBInfo* pNZBInfo); + const char* DetectStatus(NZBInfo* nzbInfo); public: virtual void Execute(); }; @@ -200,7 +200,7 @@ public: class HistoryXmlCommand: public NzbInfoXmlCommand { private: - const char* DetectStatus(HistoryInfo* pHistoryInfo); + const char* DetectStatus(HistoryInfo* historyInfo); public: virtual void Execute(); }; @@ -238,10 +238,10 @@ public: class ViewFeedXmlCommand: public XmlCommand { private: - bool m_bPreview; + bool m_preview; public: - ViewFeedXmlCommand(bool bPreview); + ViewFeedXmlCommand(bool preview); virtual void Execute(); }; @@ -298,8 +298,8 @@ class LoadLogXmlCommand: public LogXmlCommand { private: MessageList m_messages; - int m_iNZBID; - NZBInfo* m_pNZBInfo; + int m_nzbId; + NZBInfo* m_nzbInfo; protected: virtual void Execute(); virtual MessageList* LockMessages(); @@ -309,19 +309,19 @@ protected: class TestServerXmlCommand: public XmlCommand { private: - char* m_szErrText; + char* m_errText; class TestConnection : public NNTPConnection { protected: - TestServerXmlCommand* m_pOwner; - virtual void PrintError(const char* szErrMsg) { m_pOwner->PrintError(szErrMsg); } + TestServerXmlCommand* m_owner; + virtual void PrintError(const char* errMsg) { m_owner->PrintError(errMsg); } public: - TestConnection(NewsServer* pNewsServer, TestServerXmlCommand* pOwner): - NNTPConnection(pNewsServer), m_pOwner(pOwner) {} + TestConnection(NewsServer* newsServer, TestServerXmlCommand* owner): + NNTPConnection(newsServer), m_owner(owner) {} }; - void PrintError(const char* szErrMsg); + void PrintError(const char* errMsg); public: virtual void Execute(); }; @@ -332,50 +332,50 @@ public: XmlRpcProcessor::XmlRpcProcessor() { - m_szRequest = NULL; - m_eProtocol = rpUndefined; - m_eHttpMethod = hmPost; - m_szUrl = NULL; - m_szContentType = NULL; + m_request = NULL; + m_protocol = rpUndefined; + m_httpMethod = hmPost; + m_url = NULL; + m_contentType = NULL; } XmlRpcProcessor::~XmlRpcProcessor() { - free(m_szUrl); + free(m_url); } -void XmlRpcProcessor::SetUrl(const char* szUrl) +void XmlRpcProcessor::SetUrl(const char* url) { - m_szUrl = strdup(szUrl); - WebUtil::URLDecode(m_szUrl); + m_url = strdup(url); + WebUtil::URLDecode(m_url); } -bool XmlRpcProcessor::IsRpcRequest(const char* szUrl) +bool XmlRpcProcessor::IsRpcRequest(const char* url) { - return !strcmp(szUrl, "/xmlrpc") || !strncmp(szUrl, "/xmlrpc/", 8) || - !strcmp(szUrl, "/jsonrpc") || !strncmp(szUrl, "/jsonrpc/", 9) || - !strcmp(szUrl, "/jsonprpc") || !strncmp(szUrl, "/jsonprpc/", 10); + return !strcmp(url, "/xmlrpc") || !strncmp(url, "/xmlrpc/", 8) || + !strcmp(url, "/jsonrpc") || !strncmp(url, "/jsonrpc/", 9) || + !strcmp(url, "/jsonprpc") || !strncmp(url, "/jsonprpc/", 10); } void XmlRpcProcessor::Execute() { - m_eProtocol = rpUndefined; - if (!strcmp(m_szUrl, "/xmlrpc") || !strncmp(m_szUrl, "/xmlrpc/", 8)) + m_protocol = rpUndefined; + if (!strcmp(m_url, "/xmlrpc") || !strncmp(m_url, "/xmlrpc/", 8)) { - m_eProtocol = XmlRpcProcessor::rpXmlRpc; + m_protocol = XmlRpcProcessor::rpXmlRpc; } - else if (!strcmp(m_szUrl, "/jsonrpc") || !strncmp(m_szUrl, "/jsonrpc/", 9)) + else if (!strcmp(m_url, "/jsonrpc") || !strncmp(m_url, "/jsonrpc/", 9)) { - m_eProtocol = rpJsonRpc; + m_protocol = rpJsonRpc; } - else if (!strcmp(m_szUrl, "/jsonprpc") || !strncmp(m_szUrl, "/jsonprpc/", 10)) + else if (!strcmp(m_url, "/jsonprpc") || !strncmp(m_url, "/jsonprpc/", 10)) { - m_eProtocol = rpJsonPRpc; + m_protocol = rpJsonPRpc; } else { - error("internal error: invalid rpc-request: %s", m_szUrl); + error("internal error: invalid rpc-request: %s", m_url); return; } @@ -384,133 +384,133 @@ void XmlRpcProcessor::Execute() void XmlRpcProcessor::Dispatch() { - char* szRequest = m_szRequest; + char* request = m_request; - char szMethodName[100]; - szMethodName[0] = '\0'; + char methodName[100]; + methodName[0] = '\0'; - char szRequestId[100]; - szRequestId[0] = '\0'; + char requestId[100]; + requestId[0] = '\0'; - if (m_eHttpMethod == hmGet) + if (m_httpMethod == hmGet) { - szRequest = m_szUrl + 1; - char* pstart = strchr(szRequest, '/'); + request = m_url + 1; + char* pstart = strchr(request, '/'); if (pstart) { char* pend = strchr(pstart + 1, '?'); if (pend) { - int iLen = (int)(pend - pstart - 1 < (int)sizeof(szMethodName) - 1 ? pend - pstart - 1 : (int)sizeof(szMethodName) - 1); - iLen = iLen >= sizeof(szMethodName) ? sizeof(szMethodName) - 1 : iLen; - strncpy(szMethodName, pstart + 1, iLen); - szMethodName[iLen] = '\0'; - szRequest = pend + 1; + int len = (int)(pend - pstart - 1 < (int)sizeof(methodName) - 1 ? pend - pstart - 1 : (int)sizeof(methodName) - 1); + len = len >= sizeof(methodName) ? sizeof(methodName) - 1 : len; + strncpy(methodName, pstart + 1, len); + methodName[len] = '\0'; + request = pend + 1; } else { - strncpy(szMethodName, pstart + 1, sizeof(szMethodName)); - szMethodName[sizeof(szMethodName) - 1] = '\0'; - szRequest = szRequest + strlen(szRequest); + strncpy(methodName, pstart + 1, sizeof(methodName)); + methodName[sizeof(methodName) - 1] = '\0'; + request = request + strlen(request); } } } - else if (m_eProtocol == rpXmlRpc) + else if (m_protocol == rpXmlRpc) { - WebUtil::XmlParseTagValue(m_szRequest, "methodName", szMethodName, sizeof(szMethodName), NULL); + WebUtil::XmlParseTagValue(m_request, "methodName", methodName, sizeof(methodName), NULL); } - else if (m_eProtocol == rpJsonRpc) + else if (m_protocol == rpJsonRpc) { - int iValueLen = 0; - if (const char* szMethodPtr = WebUtil::JsonFindField(m_szRequest, "method", &iValueLen)) + int valueLen = 0; + if (const char* methodPtr = WebUtil::JsonFindField(m_request, "method", &valueLen)) { - iValueLen = iValueLen >= sizeof(szMethodName) ? sizeof(szMethodName) - 1 : iValueLen; - strncpy(szMethodName, szMethodPtr + 1, iValueLen - 2); - szMethodName[iValueLen - 2] = '\0'; + valueLen = valueLen >= sizeof(methodName) ? sizeof(methodName) - 1 : valueLen; + strncpy(methodName, methodPtr + 1, valueLen - 2); + methodName[valueLen - 2] = '\0'; } - if (const char* szRequestIdPtr = WebUtil::JsonFindField(m_szRequest, "id", &iValueLen)) + if (const char* requestIdPtr = WebUtil::JsonFindField(m_request, "id", &valueLen)) { - iValueLen = iValueLen >= sizeof(szRequestId) ? sizeof(szRequestId) - 1 : iValueLen; - strncpy(szRequestId, szRequestIdPtr, iValueLen); - szRequestId[iValueLen] = '\0'; + valueLen = valueLen >= sizeof(requestId) ? sizeof(requestId) - 1 : valueLen; + strncpy(requestId, requestIdPtr, valueLen); + requestId[valueLen] = '\0'; } } - debug("MethodName=%s", szMethodName); + debug("MethodName=%s", methodName); - if (!strcasecmp(szMethodName, "system.multicall") && m_eProtocol == rpXmlRpc && m_eHttpMethod == hmPost) + if (!strcasecmp(methodName, "system.multicall") && m_protocol == rpXmlRpc && m_httpMethod == hmPost) { MutliCall(); } else { - XmlCommand* command = CreateCommand(szMethodName); - command->SetRequest(szRequest); - command->SetProtocol(m_eProtocol); - command->SetHttpMethod(m_eHttpMethod); - command->SetUserAccess(m_eUserAccess); + XmlCommand* command = CreateCommand(methodName); + command->SetRequest(request); + command->SetProtocol(m_protocol); + command->SetHttpMethod(m_httpMethod); + command->SetUserAccess(m_userAccess); command->PrepareParams(); command->Execute(); - BuildResponse(command->GetResponse(), command->GetCallbackFunc(), command->GetFault(), szRequestId); + BuildResponse(command->GetResponse(), command->GetCallbackFunc(), command->GetFault(), requestId); delete command; } } void XmlRpcProcessor::MutliCall() { - bool bError = false; + bool error = false; StringBuilder cStringBuilder; cStringBuilder.Append(""); - char* szRequestPtr = m_szRequest; - char* szCallEnd = strstr(szRequestPtr, ""); - while (szCallEnd) + char* requestPtr = m_request; + char* callEnd = strstr(requestPtr, ""); + while (callEnd) { - *szCallEnd = '\0'; - debug("MutliCall, request=%s", szRequestPtr); - char* szNameEnd = strstr(szRequestPtr, ""); - if (!szNameEnd) + *callEnd = '\0'; + debug("MutliCall, request=%s", requestPtr); + char* nameEnd = strstr(requestPtr, ""); + if (!nameEnd) { - bError = true; + error = true; break; } - char szMethodName[100]; - szMethodName[0] = '\0'; - WebUtil::XmlParseTagValue(szNameEnd, "string", szMethodName, sizeof(szMethodName), NULL); - debug("MutliCall, MethodName=%s", szMethodName); + char methodName[100]; + methodName[0] = '\0'; + WebUtil::XmlParseTagValue(nameEnd, "string", methodName, sizeof(methodName), NULL); + debug("MutliCall, MethodName=%s", methodName); - XmlCommand* command = CreateCommand(szMethodName); - command->SetRequest(szRequestPtr); + XmlCommand* command = CreateCommand(methodName); + command->SetRequest(requestPtr); command->Execute(); debug("MutliCall, Response=%s", command->GetResponse()); - bool bFault = !strncmp(command->GetResponse(), "", 7); - bool bArray = !bFault && !strncmp(command->GetResponse(), "", 7); - if (!bFault && !bArray) + bool fault = !strncmp(command->GetResponse(), "", 7); + bool array = !fault && !strncmp(command->GetResponse(), "", 7); + if (!fault && !array) { cStringBuilder.Append(""); } cStringBuilder.Append(""); cStringBuilder.Append(command->GetResponse()); cStringBuilder.Append(""); - if (!bFault && !bArray) + if (!fault && !array) { cStringBuilder.Append(""); } delete command; - szRequestPtr = szCallEnd + 9; //strlen("") - szCallEnd = strstr(szRequestPtr, ""); + requestPtr = callEnd + 9; //strlen("") + callEnd = strstr(requestPtr, ""); } - if (bError) + if (error) { XmlCommand* command = new ErrorXmlCommand(4, "Parse error"); - command->SetRequest(m_szRequest); + command->SetRequest(m_request); command->SetProtocol(rpXmlRpc); command->PrepareParams(); command->Execute(); @@ -524,8 +524,8 @@ void XmlRpcProcessor::MutliCall() } } -void XmlRpcProcessor::BuildResponse(const char* szResponse, const char* szCallbackFunc, - bool bFault, const char* szRequestId) +void XmlRpcProcessor::BuildResponse(const char* response, const char* callbackFunc, + bool fault, const char* requestId) { const char XML_HEADER[] = "\n\n"; const char XML_FOOTER[] = ""; @@ -546,213 +546,213 @@ void XmlRpcProcessor::BuildResponse(const char* szResponse, const char* szCallba const char JSONP_CALLBACK_HEADER[] = "("; const char JSONP_CALLBACK_FOOTER[] = ")"; - bool bXmlRpc = m_eProtocol == rpXmlRpc; + bool xmlRpc = m_protocol == rpXmlRpc; - const char* szCallbackHeader = m_eProtocol == rpJsonPRpc ? JSONP_CALLBACK_HEADER : ""; - const char* szHeader = bXmlRpc ? XML_HEADER : JSON_HEADER; - const char* szFooter = bXmlRpc ? XML_FOOTER : JSON_FOOTER; - const char* szOpenTag = bFault ? (bXmlRpc ? XML_FAULT_OPEN : JSON_FAULT_OPEN) : (bXmlRpc ? XML_OK_OPEN : JSON_OK_OPEN); - const char* szCloseTag = bFault ? (bXmlRpc ? XML_FAULT_CLOSE : JSON_FAULT_CLOSE ) : (bXmlRpc ? XML_OK_CLOSE : JSON_OK_CLOSE); - const char* szCallbackFooter = m_eProtocol == rpJsonPRpc ? JSONP_CALLBACK_FOOTER : ""; + const char* callbackHeader = m_protocol == rpJsonPRpc ? JSONP_CALLBACK_HEADER : ""; + const char* header = xmlRpc ? XML_HEADER : JSON_HEADER; + const char* footer = xmlRpc ? XML_FOOTER : JSON_FOOTER; + const char* openTag = fault ? (xmlRpc ? XML_FAULT_OPEN : JSON_FAULT_OPEN) : (xmlRpc ? XML_OK_OPEN : JSON_OK_OPEN); + const char* closeTag = fault ? (xmlRpc ? XML_FAULT_CLOSE : JSON_FAULT_CLOSE ) : (xmlRpc ? XML_OK_CLOSE : JSON_OK_CLOSE); + const char* callbackFooter = m_protocol == rpJsonPRpc ? JSONP_CALLBACK_FOOTER : ""; - debug("Response=%s", szResponse); + debug("Response=%s", response); - if (szCallbackFunc) + if (callbackFunc) { - m_cResponse.Append(szCallbackFunc); + m_cResponse.Append(callbackFunc); } - m_cResponse.Append(szCallbackHeader); - m_cResponse.Append(szHeader); - if (!bXmlRpc && szRequestId && *szRequestId) + m_cResponse.Append(callbackHeader); + m_cResponse.Append(header); + if (!xmlRpc && requestId && *requestId) { m_cResponse.Append(JSON_ID_OPEN); - m_cResponse.Append(szRequestId); + m_cResponse.Append(requestId); m_cResponse.Append(JSON_ID_CLOSE); } - m_cResponse.Append(szOpenTag); - m_cResponse.Append(szResponse); - m_cResponse.Append(szCloseTag); - m_cResponse.Append(szFooter); - m_cResponse.Append(szCallbackFooter); + m_cResponse.Append(openTag); + m_cResponse.Append(response); + m_cResponse.Append(closeTag); + m_cResponse.Append(footer); + m_cResponse.Append(callbackFooter); - m_szContentType = bXmlRpc ? "text/xml" : "application/json"; + m_contentType = xmlRpc ? "text/xml" : "application/json"; } -XmlCommand* XmlRpcProcessor::CreateCommand(const char* szMethodName) +XmlCommand* XmlRpcProcessor::CreateCommand(const char* methodName) { XmlCommand* command = NULL; - if (m_eUserAccess == uaAdd && - !(!strcasecmp(szMethodName, "append") || !strcasecmp(szMethodName, "appendurl") || - !strcasecmp(szMethodName, "version"))) + if (m_userAccess == uaAdd && + !(!strcasecmp(methodName, "append") || !strcasecmp(methodName, "appendurl") || + !strcasecmp(methodName, "version"))) { command = new ErrorXmlCommand(401, "Access denied"); - warn("Received request \"%s\" from add-user, access denied", szMethodName); + warn("Received request \"%s\" from add-user, access denied", methodName); } - else if (m_eUserAccess == uaRestricted && !strcasecmp(szMethodName, "saveconfig")) + else if (m_userAccess == uaRestricted && !strcasecmp(methodName, "saveconfig")) { command = new ErrorXmlCommand(401, "Access denied"); - warn("Received request \"%s\" from restricted user, access denied", szMethodName); + warn("Received request \"%s\" from restricted user, access denied", methodName); } - else if (!strcasecmp(szMethodName, "pause") || !strcasecmp(szMethodName, "pausedownload") || - !strcasecmp(szMethodName, "pausedownload2")) + else if (!strcasecmp(methodName, "pause") || !strcasecmp(methodName, "pausedownload") || + !strcasecmp(methodName, "pausedownload2")) { command = new PauseUnpauseXmlCommand(true, PauseUnpauseXmlCommand::paDownload); } - else if (!strcasecmp(szMethodName, "resume") || !strcasecmp(szMethodName, "resumedownload") || - !strcasecmp(szMethodName, "resumedownload2")) + else if (!strcasecmp(methodName, "resume") || !strcasecmp(methodName, "resumedownload") || + !strcasecmp(methodName, "resumedownload2")) { command = new PauseUnpauseXmlCommand(false, PauseUnpauseXmlCommand::paDownload); } - else if (!strcasecmp(szMethodName, "shutdown")) + else if (!strcasecmp(methodName, "shutdown")) { command = new ShutdownXmlCommand(); } - else if (!strcasecmp(szMethodName, "reload")) + else if (!strcasecmp(methodName, "reload")) { command = new ReloadXmlCommand(); } - else if (!strcasecmp(szMethodName, "version")) + else if (!strcasecmp(methodName, "version")) { command = new VersionXmlCommand(); } - else if (!strcasecmp(szMethodName, "dump")) + else if (!strcasecmp(methodName, "dump")) { command = new DumpDebugXmlCommand(); } - else if (!strcasecmp(szMethodName, "rate")) + else if (!strcasecmp(methodName, "rate")) { command = new SetDownloadRateXmlCommand(); } - else if (!strcasecmp(szMethodName, "status")) + else if (!strcasecmp(methodName, "status")) { command = new StatusXmlCommand(); } - else if (!strcasecmp(szMethodName, "log")) + else if (!strcasecmp(methodName, "log")) { command = new LogXmlCommand(); } - else if (!strcasecmp(szMethodName, "listfiles")) + else if (!strcasecmp(methodName, "listfiles")) { command = new ListFilesXmlCommand(); } - else if (!strcasecmp(szMethodName, "listgroups")) + else if (!strcasecmp(methodName, "listgroups")) { command = new ListGroupsXmlCommand(); } - else if (!strcasecmp(szMethodName, "editqueue")) + else if (!strcasecmp(methodName, "editqueue")) { command = new EditQueueXmlCommand(); } - else if (!strcasecmp(szMethodName, "append") || !strcasecmp(szMethodName, "appendurl")) + else if (!strcasecmp(methodName, "append") || !strcasecmp(methodName, "appendurl")) { command = new DownloadXmlCommand(); } - else if (!strcasecmp(szMethodName, "postqueue")) + else if (!strcasecmp(methodName, "postqueue")) { command = new PostQueueXmlCommand(); } - else if (!strcasecmp(szMethodName, "writelog")) + else if (!strcasecmp(methodName, "writelog")) { command = new WriteLogXmlCommand(); } - else if (!strcasecmp(szMethodName, "clearlog")) + else if (!strcasecmp(methodName, "clearlog")) { command = new ClearLogXmlCommand(); } - else if (!strcasecmp(szMethodName, "loadlog")) + else if (!strcasecmp(methodName, "loadlog")) { command = new LoadLogXmlCommand(); } - else if (!strcasecmp(szMethodName, "scan")) + else if (!strcasecmp(methodName, "scan")) { command = new ScanXmlCommand(); } - else if (!strcasecmp(szMethodName, "pausepost")) + else if (!strcasecmp(methodName, "pausepost")) { command = new PauseUnpauseXmlCommand(true, PauseUnpauseXmlCommand::paPostProcess); } - else if (!strcasecmp(szMethodName, "resumepost")) + else if (!strcasecmp(methodName, "resumepost")) { command = new PauseUnpauseXmlCommand(false, PauseUnpauseXmlCommand::paPostProcess); } - else if (!strcasecmp(szMethodName, "pausescan")) + else if (!strcasecmp(methodName, "pausescan")) { command = new PauseUnpauseXmlCommand(true, PauseUnpauseXmlCommand::paScan); } - else if (!strcasecmp(szMethodName, "resumescan")) + else if (!strcasecmp(methodName, "resumescan")) { command = new PauseUnpauseXmlCommand(false, PauseUnpauseXmlCommand::paScan); } - else if (!strcasecmp(szMethodName, "scheduleresume")) + else if (!strcasecmp(methodName, "scheduleresume")) { command = new ScheduleResumeXmlCommand(); } - else if (!strcasecmp(szMethodName, "history")) + else if (!strcasecmp(methodName, "history")) { command = new HistoryXmlCommand(); } - else if (!strcasecmp(szMethodName, "urlqueue")) + else if (!strcasecmp(methodName, "urlqueue")) { command = new UrlQueueXmlCommand(); } - else if (!strcasecmp(szMethodName, "config")) + else if (!strcasecmp(methodName, "config")) { command = new ConfigXmlCommand(); } - else if (!strcasecmp(szMethodName, "loadconfig")) + else if (!strcasecmp(methodName, "loadconfig")) { command = new LoadConfigXmlCommand(); } - else if (!strcasecmp(szMethodName, "saveconfig")) + else if (!strcasecmp(methodName, "saveconfig")) { command = new SaveConfigXmlCommand(); } - else if (!strcasecmp(szMethodName, "configtemplates")) + else if (!strcasecmp(methodName, "configtemplates")) { command = new ConfigTemplatesXmlCommand(); } - else if (!strcasecmp(szMethodName, "viewfeed")) + else if (!strcasecmp(methodName, "viewfeed")) { command = new ViewFeedXmlCommand(false); } - else if (!strcasecmp(szMethodName, "previewfeed")) + else if (!strcasecmp(methodName, "previewfeed")) { command = new ViewFeedXmlCommand(true); } - else if (!strcasecmp(szMethodName, "fetchfeed")) + else if (!strcasecmp(methodName, "fetchfeed")) { command = new FetchFeedXmlCommand(); } - else if (!strcasecmp(szMethodName, "editserver")) + else if (!strcasecmp(methodName, "editserver")) { command = new EditServerXmlCommand(); } - else if (!strcasecmp(szMethodName, "readurl")) + else if (!strcasecmp(methodName, "readurl")) { command = new ReadUrlXmlCommand(); } - else if (!strcasecmp(szMethodName, "checkupdates")) + else if (!strcasecmp(methodName, "checkupdates")) { command = new CheckUpdatesXmlCommand(); } - else if (!strcasecmp(szMethodName, "startupdate")) + else if (!strcasecmp(methodName, "startupdate")) { command = new StartUpdateXmlCommand(); } - else if (!strcasecmp(szMethodName, "logupdate")) + else if (!strcasecmp(methodName, "logupdate")) { command = new LogUpdateXmlCommand(); } - else if (!strcasecmp(szMethodName, "servervolumes")) + else if (!strcasecmp(methodName, "servervolumes")) { command = new ServerVolumesXmlCommand(); } - else if (!strcasecmp(szMethodName, "resetservervolume")) + else if (!strcasecmp(methodName, "resetservervolume")) { command = new ResetServerVolumeXmlCommand(); } - else if (!strcasecmp(szMethodName, "testserver")) + else if (!strcasecmp(methodName, "testserver")) { command = new TestServerXmlCommand(); } @@ -770,51 +770,51 @@ XmlCommand* XmlRpcProcessor::CreateCommand(const char* szMethodName) XmlCommand::XmlCommand() { - m_szRequest = NULL; - m_szRequestPtr = NULL; - m_szCallbackFunc = NULL; - m_bFault = false; - m_eProtocol = XmlRpcProcessor::rpUndefined; - m_StringBuilder.SetGrowSize(1024 * 10); + m_request = NULL; + m_requestPtr = NULL; + m_callbackFunc = NULL; + m_fault = false; + m_protocol = XmlRpcProcessor::rpUndefined; + m_stringBuilder.SetGrowSize(1024 * 10); } bool XmlCommand::IsJson() { - return m_eProtocol == XmlRpcProcessor::rpJsonRpc || m_eProtocol == XmlRpcProcessor::rpJsonPRpc; + return m_protocol == XmlRpcProcessor::rpJsonRpc || m_protocol == XmlRpcProcessor::rpJsonPRpc; } -void XmlCommand::AppendResponse(const char* szPart) +void XmlCommand::AppendResponse(const char* part) { - m_StringBuilder.Append(szPart); + m_stringBuilder.Append(part); } -void XmlCommand::AppendFmtResponse(const char* szFormat, ...) +void XmlCommand::AppendFmtResponse(const char* format, ...) { va_list args; - va_start(args, szFormat); - m_StringBuilder.AppendFmtV(szFormat, args); + va_start(args, format); + m_stringBuilder.AppendFmtV(format, args); va_end(args); } -void XmlCommand::AppendCondResponse(const char* szPart, bool bCond) +void XmlCommand::AppendCondResponse(const char* part, bool cond) { - if (bCond) + if (cond) { - m_StringBuilder.Append(szPart); + m_stringBuilder.Append(part); } } -void XmlCommand::OptimizeResponse(int iRecordCount) +void XmlCommand::OptimizeResponse(int recordCount) { // Reduce the number of memory allocations when building response buffer - int iGrowSize = iRecordCount * m_StringBuilder.GetUsedSize() / 10; - if (iGrowSize > 1024 * 10) + int growSize = recordCount * m_stringBuilder.GetUsedSize() / 10; + if (growSize > 1024 * 10) { - m_StringBuilder.SetGrowSize(iGrowSize); + m_stringBuilder.SetGrowSize(growSize); } } -void XmlCommand::BuildErrorResponse(int iErrCode, const char* szErrText, ...) +void XmlCommand::BuildErrorResponse(int errCode, const char* errText, ...) { const char* XML_RESPONSE_ERROR_BODY = "\n" @@ -829,183 +829,183 @@ void XmlCommand::BuildErrorResponse(int iErrCode, const char* szErrText, ...) "\"message\" : \"%s\"\n" "}"; - char szFullText[1024]; + char fullText[1024]; va_list ap; - va_start(ap, szErrText); - vsnprintf(szFullText, 1024, szErrText, ap); - szFullText[1024-1] = '\0'; + va_start(ap, errText); + vsnprintf(fullText, 1024, errText, ap); + fullText[1024-1] = '\0'; va_end(ap); - char* xmlText = EncodeStr(szFullText); + char* xmlText = EncodeStr(fullText); - char szContent[1024]; - snprintf(szContent, 1024, IsJson() ? JSON_RESPONSE_ERROR_BODY : XML_RESPONSE_ERROR_BODY, iErrCode, xmlText); - szContent[1024-1] = '\0'; + char content[1024]; + snprintf(content, 1024, IsJson() ? JSON_RESPONSE_ERROR_BODY : XML_RESPONSE_ERROR_BODY, errCode, xmlText); + content[1024-1] = '\0'; free(xmlText); - AppendResponse(szContent); + AppendResponse(content); - m_bFault = true; + m_fault = true; } -void XmlCommand::BuildBoolResponse(bool bOK) +void XmlCommand::BuildBoolResponse(bool ok) { const char* XML_RESPONSE_BOOL_BODY = "%s"; const char* JSON_RESPONSE_BOOL_BODY = "%s"; - char szContent[1024]; - snprintf(szContent, 1024, IsJson() ? JSON_RESPONSE_BOOL_BODY : XML_RESPONSE_BOOL_BODY, - BoolToStr(bOK)); - szContent[1024-1] = '\0'; + char content[1024]; + snprintf(content, 1024, IsJson() ? JSON_RESPONSE_BOOL_BODY : XML_RESPONSE_BOOL_BODY, + BoolToStr(ok)); + content[1024-1] = '\0'; - AppendResponse(szContent); + AppendResponse(content); } -void XmlCommand::BuildIntResponse(int iValue) +void XmlCommand::BuildIntResponse(int value) { const char* XML_RESPONSE_INT_BODY = "%i"; const char* JSON_RESPONSE_INT_BODY = "%i"; - char szContent[1024]; - snprintf(szContent, 1024, IsJson() ? JSON_RESPONSE_INT_BODY : XML_RESPONSE_INT_BODY, iValue); - szContent[1024-1] = '\0'; + char content[1024]; + snprintf(content, 1024, IsJson() ? JSON_RESPONSE_INT_BODY : XML_RESPONSE_INT_BODY, value); + content[1024-1] = '\0'; - AppendResponse(szContent); + AppendResponse(content); } void XmlCommand::PrepareParams() { - if (IsJson() && m_eHttpMethod == XmlRpcProcessor::hmPost) + if (IsJson() && m_httpMethod == XmlRpcProcessor::hmPost) { - char* szParams = strstr(m_szRequestPtr, "\"params\""); - if (!szParams) + char* params = strstr(m_requestPtr, "\"params\""); + if (!params) { - m_szRequestPtr[0] = '\0'; + m_requestPtr[0] = '\0'; return; } - m_szRequestPtr = szParams + 8; // strlen("\"params\"") + m_requestPtr = params + 8; // strlen("\"params\"") } - if (m_eProtocol == XmlRpcProcessor::rpJsonPRpc) + if (m_protocol == XmlRpcProcessor::rpJsonPRpc) { - NextParamAsStr(&m_szCallbackFunc); + NextParamAsStr(&m_callbackFunc); } } -char* XmlCommand::XmlNextValue(char* szXml, const char* szTag, int* pValueLength) +char* XmlCommand::XmlNextValue(char* xml, const char* tag, int* valueLength) { - int iValueLen; - const char* szValue = WebUtil::XmlFindTag(szXml, "value", &iValueLen); - if (szValue) + int valueLen; + const char* value = WebUtil::XmlFindTag(xml, "value", &valueLen); + if (value) { - char* szTagContent = (char*)WebUtil::XmlFindTag(szValue, szTag, pValueLength); - if (szTagContent <= szValue + iValueLen) + char* tagContent = (char*)WebUtil::XmlFindTag(value, tag, valueLength); + if (tagContent <= value + valueLen) { - return szTagContent; + return tagContent; } } return NULL; } -bool XmlCommand::NextParamAsInt(int* iValue) +bool XmlCommand::NextParamAsInt(int* value) { - if (m_eHttpMethod == XmlRpcProcessor::hmGet) + if (m_httpMethod == XmlRpcProcessor::hmGet) { - char* szParam = strchr(m_szRequestPtr, '='); - if (!szParam) + char* param = strchr(m_requestPtr, '='); + if (!param) { return false; } - *iValue = atoi(szParam + 1); - m_szRequestPtr = szParam + 1; - while (strchr("-+0123456789&", *m_szRequestPtr)) + *value = atoi(param + 1); + m_requestPtr = param + 1; + while (strchr("-+0123456789&", *m_requestPtr)) { - m_szRequestPtr++; + m_requestPtr++; } return true; } else if (IsJson()) { - int iLen = 0; - char* szParam = (char*)WebUtil::JsonNextValue(m_szRequestPtr, &iLen); - if (!szParam || !strchr("-+0123456789", *szParam)) + int len = 0; + char* param = (char*)WebUtil::JsonNextValue(m_requestPtr, &len); + if (!param || !strchr("-+0123456789", *param)) { return false; } - *iValue = atoi(szParam); - m_szRequestPtr = szParam + iLen + 1; + *value = atoi(param); + m_requestPtr = param + len + 1; return true; } else { - int iLen = 0; - int iTagLen = 4; //strlen(""); - char* szParam = XmlNextValue(m_szRequestPtr, "i4", &iLen); - if (!szParam) + int len = 0; + int tagLen = 4; //strlen(""); + char* param = XmlNextValue(m_requestPtr, "i4", &len); + if (!param) { - szParam = XmlNextValue(m_szRequestPtr, "int", &iLen); - iTagLen = 5; //strlen(""); + param = XmlNextValue(m_requestPtr, "int", &len); + tagLen = 5; //strlen(""); } - if (!szParam || !strchr("-+0123456789", *szParam)) + if (!param || !strchr("-+0123456789", *param)) { return false; } - *iValue = atoi(szParam); - m_szRequestPtr = szParam + iLen + iTagLen; + *value = atoi(param); + m_requestPtr = param + len + tagLen; return true; } } -bool XmlCommand::NextParamAsBool(bool* bValue) +bool XmlCommand::NextParamAsBool(bool* value) { - if (m_eHttpMethod == XmlRpcProcessor::hmGet) + if (m_httpMethod == XmlRpcProcessor::hmGet) { - char* szParam; - if (!NextParamAsStr(&szParam)) + char* param; + if (!NextParamAsStr(¶m)) { return false; } if (IsJson()) { - if (!strncmp(szParam, "true", 4)) + if (!strncmp(param, "true", 4)) { - *bValue = true; + *value = true; return true; } - else if (!strncmp(szParam, "false", 5)) + else if (!strncmp(param, "false", 5)) { - *bValue = false; + *value = false; return true; } } else { - *bValue = szParam[0] == '1'; + *value = param[0] == '1'; return true; } return false; } else if (IsJson()) { - int iLen = 0; - char* szParam = (char*)WebUtil::JsonNextValue(m_szRequestPtr, &iLen); - if (!szParam) + int len = 0; + char* param = (char*)WebUtil::JsonNextValue(m_requestPtr, &len); + if (!param) { return false; } - if (iLen == 4 && !strncmp(szParam, "true", 4)) + if (len == 4 && !strncmp(param, "true", 4)) { - *bValue = true; - m_szRequestPtr = szParam + iLen + 1; + *value = true; + m_requestPtr = param + len + 1; return true; } - else if (iLen == 5 && !strncmp(szParam, "false", 5)) + else if (len == 5 && !strncmp(param, "false", 5)) { - *bValue = false; - m_szRequestPtr = szParam + iLen + 1; + *value = false; + m_requestPtr = param + len + 1; return true; } else @@ -1015,134 +1015,134 @@ bool XmlCommand::NextParamAsBool(bool* bValue) } else { - int iLen = 0; - char* szParam = XmlNextValue(m_szRequestPtr, "boolean", &iLen); - if (!szParam) + int len = 0; + char* param = XmlNextValue(m_requestPtr, "boolean", &len); + if (!param) { return false; } - *bValue = szParam[0] == '1'; - m_szRequestPtr = szParam + iLen + 9; //strlen(""); + *value = param[0] == '1'; + m_requestPtr = param + len + 9; //strlen(""); return true; } } -bool XmlCommand::NextParamAsStr(char** szValue) +bool XmlCommand::NextParamAsStr(char** value) { - if (m_eHttpMethod == XmlRpcProcessor::hmGet) + if (m_httpMethod == XmlRpcProcessor::hmGet) { - char* szParam = strchr(m_szRequestPtr, '='); - if (!szParam) + char* param = strchr(m_requestPtr, '='); + if (!param) { return false; } - szParam++; // skip '=' - int iLen = 0; - char* szParamEnd = strchr(szParam, '&'); - if (szParamEnd) + param++; // skip '=' + int len = 0; + char* paramEnd = strchr(param, '&'); + if (paramEnd) { - iLen = (int)(szParamEnd - szParam); - szParam[iLen] = '\0'; + len = (int)(paramEnd - param); + param[len] = '\0'; } else { - iLen = strlen(szParam) - 1; + len = strlen(param) - 1; } - m_szRequestPtr = szParam + iLen + 1; - *szValue = szParam; + m_requestPtr = param + len + 1; + *value = param; return true; } else if (IsJson()) { - int iLen = 0; - char* szParam = (char*)WebUtil::JsonNextValue(m_szRequestPtr, &iLen); - if (!szParam || iLen < 2 || szParam[0] != '"' || szParam[iLen - 1] != '"') + int len = 0; + char* param = (char*)WebUtil::JsonNextValue(m_requestPtr, &len); + if (!param || len < 2 || param[0] != '"' || param[len - 1] != '"') { return false; } - szParam++; // skip first '"' - szParam[iLen - 2] = '\0'; // skip last '"' - m_szRequestPtr = szParam + iLen; - *szValue = szParam; + param++; // skip first '"' + param[len - 2] = '\0'; // skip last '"' + m_requestPtr = param + len; + *value = param; return true; } else { - int iLen = 0; - char* szParam = XmlNextValue(m_szRequestPtr, "string", &iLen); - if (!szParam) + int len = 0; + char* param = XmlNextValue(m_requestPtr, "string", &len); + if (!param) { return false; } - szParam[iLen] = '\0'; - m_szRequestPtr = szParam + iLen + 8; //strlen("") - *szValue = szParam; + param[len] = '\0'; + m_requestPtr = param + len + 8; //strlen("") + *value = param; return true; } } -const char* XmlCommand::BoolToStr(bool bValue) +const char* XmlCommand::BoolToStr(bool value) { - return IsJson() ? (bValue ? "true" : "false") : (bValue ? "1" : "0"); + return IsJson() ? (value ? "true" : "false") : (value ? "1" : "0"); } -char* XmlCommand::EncodeStr(const char* szStr) +char* XmlCommand::EncodeStr(const char* str) { - if (!szStr) + if (!str) { return strdup(""); } if (IsJson()) { - return WebUtil::JsonEncode(szStr); + return WebUtil::JsonEncode(str); } else { - return WebUtil::XmlEncode(szStr); + return WebUtil::XmlEncode(str); } } -void XmlCommand::DecodeStr(char* szStr) +void XmlCommand::DecodeStr(char* str) { if (IsJson()) { - WebUtil::JsonDecode(szStr); + WebUtil::JsonDecode(str); } else { - WebUtil::XmlDecode(szStr); + WebUtil::XmlDecode(str); } } bool XmlCommand::CheckSafeMethod() { - bool bSafe = m_eHttpMethod == XmlRpcProcessor::hmPost || m_eProtocol == XmlRpcProcessor::rpJsonPRpc; - if (!bSafe) + bool safe = m_httpMethod == XmlRpcProcessor::hmPost || m_protocol == XmlRpcProcessor::rpJsonPRpc; + if (!safe) { BuildErrorResponse(4, "Not safe procedure for HTTP-Method GET. Use Method POST instead"); } - return bSafe; + return safe; } //***************************************************************** // Commands -ErrorXmlCommand::ErrorXmlCommand(int iErrCode, const char* szErrText) +ErrorXmlCommand::ErrorXmlCommand(int errCode, const char* errText) { - m_iErrCode = iErrCode; - m_szErrText = szErrText; + m_errCode = errCode; + m_errText = errText; } void ErrorXmlCommand::Execute() { - BuildErrorResponse(m_iErrCode, m_szErrText); + BuildErrorResponse(m_errCode, m_errText); } -PauseUnpauseXmlCommand::PauseUnpauseXmlCommand(bool bPause, EPauseAction eEPauseAction) +PauseUnpauseXmlCommand::PauseUnpauseXmlCommand(bool pause, EPauseAction ePauseAction) { - m_bPause = bPause; - m_eEPauseAction = eEPauseAction; + m_pause = pause; + m_ePauseAction = ePauseAction; } void PauseUnpauseXmlCommand::Execute() @@ -1152,29 +1152,29 @@ void PauseUnpauseXmlCommand::Execute() return; } - bool bOK = true; + bool ok = true; g_pOptions->SetResumeTime(0); - switch (m_eEPauseAction) + switch (m_ePauseAction) { case paDownload: - g_pOptions->SetPauseDownload(m_bPause); + g_pOptions->SetPauseDownload(m_pause); break; case paPostProcess: - g_pOptions->SetPausePostProcess(m_bPause); + g_pOptions->SetPausePostProcess(m_pause); break; case paScan: - g_pOptions->SetPauseScan(m_bPause); + g_pOptions->SetPauseScan(m_pause); break; default: - bOK = false; + ok = false; } - BuildBoolResponse(bOK); + BuildBoolResponse(ok); } // bool scheduleresume(int Seconds) @@ -1185,16 +1185,16 @@ void ScheduleResumeXmlCommand::Execute() return; } - int iSeconds = 0; - if (!NextParamAsInt(&iSeconds) || iSeconds < 0) + int seconds = 0; + if (!NextParamAsInt(&seconds) || seconds < 0) { BuildErrorResponse(2, "Invalid parameter"); return; } - time_t tCurTime = time(NULL); + time_t curTime = time(NULL); - g_pOptions->SetResumeTime(tCurTime + iSeconds); + g_pOptions->SetResumeTime(curTime + seconds); BuildBoolResponse(true); } @@ -1226,11 +1226,11 @@ void VersionXmlCommand::Execute() const char* XML_RESPONSE_STRING_BODY = "%s"; const char* JSON_RESPONSE_STRING_BODY = "\"%s\""; - char szContent[1024]; - snprintf(szContent, 1024, IsJson() ? JSON_RESPONSE_STRING_BODY : XML_RESPONSE_STRING_BODY, Util::VersionRevision()); - szContent[1024-1] = '\0'; + char content[1024]; + snprintf(content, 1024, IsJson() ? JSON_RESPONSE_STRING_BODY : XML_RESPONSE_STRING_BODY, Util::VersionRevision()); + content[1024-1] = '\0'; - AppendResponse(szContent); + AppendResponse(content); } void DumpDebugXmlCommand::Execute() @@ -1246,14 +1246,14 @@ void SetDownloadRateXmlCommand::Execute() return; } - int iRate = 0; - if (!NextParamAsInt(&iRate) || iRate < 0) + int rate = 0; + if (!NextParamAsInt(&rate) || rate < 0) { BuildErrorResponse(2, "Invalid parameter"); return; } - g_pOptions->SetDownloadRate(iRate * 1024); + g_pOptions->SetDownloadRate(rate * 1024); BuildBoolResponse(true); } @@ -1355,75 +1355,75 @@ void StatusXmlCommand::Execute() "\"Active\" : %s\n" "}"; - DownloadQueue *pDownloadQueue = DownloadQueue::Lock(); - int iPostJobCount = 0; - int iUrlCount = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + DownloadQueue *downloadQueue = DownloadQueue::Lock(); + int postJobCount = 0; + int urlCount = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - iPostJobCount += pNZBInfo->GetPostInfo() ? 1 : 0; - iUrlCount += pNZBInfo->GetKind() == NZBInfo::nkUrl ? 1 : 0; + NZBInfo* nzbInfo = *it; + postJobCount += nzbInfo->GetPostInfo() ? 1 : 0; + urlCount += nzbInfo->GetKind() == NZBInfo::nkUrl ? 1 : 0; } - long long iRemainingSize, iForcedSize; - pDownloadQueue->CalcRemainingSize(&iRemainingSize, &iForcedSize); + long long remainingSize, forcedSize; + downloadQueue->CalcRemainingSize(&remainingSize, &forcedSize); DownloadQueue::Unlock(); - unsigned long iRemainingSizeHi, iRemainingSizeLo; - Util::SplitInt64(iRemainingSize, &iRemainingSizeHi, &iRemainingSizeLo); - int iRemainingMBytes = (int)(iRemainingSize / 1024 / 1024); + unsigned long remainingSizeHi, remainingSizeLo; + Util::SplitInt64(remainingSize, &remainingSizeHi, &remainingSizeLo); + int remainingMBytes = (int)(remainingSize / 1024 / 1024); - unsigned long iForcedSizeHi, iForcedSizeLo; - Util::SplitInt64(iForcedSize, &iForcedSizeHi, &iForcedSizeLo); - int iForcedMBytes = (int)(iForcedSize / 1024 / 1024); + unsigned long forcedSizeHi, forcedSizeLo; + Util::SplitInt64(forcedSize, &forcedSizeHi, &forcedSizeLo); + int forcedMBytes = (int)(forcedSize / 1024 / 1024); - long long iArticleCache = g_pArticleCache->GetAllocated(); - unsigned long iArticleCacheHi, iArticleCacheLo; - Util::SplitInt64(iArticleCache, &iArticleCacheHi, &iArticleCacheLo); - int iArticleCacheMBytes = (int)(iArticleCache / 1024 / 1024); + long long articleCache = g_pArticleCache->GetAllocated(); + unsigned long articleCacheHi, articleCacheLo; + Util::SplitInt64(articleCache, &articleCacheHi, &articleCacheLo); + int articleCacheMBytes = (int)(articleCache / 1024 / 1024); - int iDownloadRate = (int)(g_pStatMeter->CalcCurrentDownloadSpeed()); - int iDownloadLimit = (int)(g_pOptions->GetDownloadRate()); - bool bDownloadPaused = g_pOptions->GetPauseDownload(); - bool bPostPaused = g_pOptions->GetPausePostProcess(); - bool bScanPaused = g_pOptions->GetPauseScan(); - int iThreadCount = Thread::GetThreadCount() - 1; // not counting itself + int downloadRate = (int)(g_pStatMeter->CalcCurrentDownloadSpeed()); + int downloadLimit = (int)(g_pOptions->GetDownloadRate()); + bool downloadPaused = g_pOptions->GetPauseDownload(); + bool postPaused = g_pOptions->GetPausePostProcess(); + bool scanPaused = g_pOptions->GetPauseScan(); + int threadCount = Thread::GetThreadCount() - 1; // not counting itself - unsigned long iDownloadedSizeHi, iDownloadedSizeLo; - int iUpTimeSec, iDownloadTimeSec; - long long iAllBytes; - bool bServerStandBy; - g_pStatMeter->CalcTotalStat(&iUpTimeSec, &iDownloadTimeSec, &iAllBytes, &bServerStandBy); - int iDownloadedMBytes = (int)(iAllBytes / 1024 / 1024); - Util::SplitInt64(iAllBytes, &iDownloadedSizeHi, &iDownloadedSizeLo); - int iAverageDownloadRate = (int)(iDownloadTimeSec > 0 ? iAllBytes / iDownloadTimeSec : 0); - unsigned long iFreeDiskSpaceHi, iFreeDiskSpaceLo; - long long iFreeDiskSpace = Util::FreeDiskSize(g_pOptions->GetDestDir()); - Util::SplitInt64(iFreeDiskSpace, &iFreeDiskSpaceHi, &iFreeDiskSpaceLo); - int iFreeDiskSpaceMB = (int)(iFreeDiskSpace / 1024 / 1024); - int iServerTime = time(NULL); - int iResumeTime = g_pOptions->GetResumeTime(); - bool bFeedActive = g_pFeedCoordinator->HasActiveDownloads(); - int iQueuedScripts = g_pQueueScriptCoordinator->GetQueueSize(); + unsigned long downloadedSizeHi, downloadedSizeLo; + int upTimeSec, downloadTimeSec; + long long allBytes; + bool serverStandBy; + g_pStatMeter->CalcTotalStat(&upTimeSec, &downloadTimeSec, &allBytes, &serverStandBy); + int downloadedMBytes = (int)(allBytes / 1024 / 1024); + Util::SplitInt64(allBytes, &downloadedSizeHi, &downloadedSizeLo); + int averageDownloadRate = (int)(downloadTimeSec > 0 ? allBytes / downloadTimeSec : 0); + unsigned long freeDiskSpaceHi, freeDiskSpaceLo; + long long freeDiskSpace = Util::FreeDiskSize(g_pOptions->GetDestDir()); + Util::SplitInt64(freeDiskSpace, &freeDiskSpaceHi, &freeDiskSpaceLo); + int freeDiskSpaceMB = (int)(freeDiskSpace / 1024 / 1024); + int serverTime = time(NULL); + int resumeTime = g_pOptions->GetResumeTime(); + bool feedActive = g_pFeedCoordinator->HasActiveDownloads(); + int queuedScripts = g_pQueueScriptCoordinator->GetQueueSize(); AppendFmtResponse(IsJson() ? JSON_STATUS_START : XML_STATUS_START, - iRemainingSizeLo, iRemainingSizeHi, iRemainingMBytes, iForcedSizeLo, - iForcedSizeHi, iForcedMBytes, iDownloadedSizeLo, iDownloadedSizeHi, - iDownloadedMBytes, iArticleCacheLo, iArticleCacheHi, iArticleCacheMBytes, - iDownloadRate, iAverageDownloadRate, iDownloadLimit, iThreadCount, - iPostJobCount, iPostJobCount, iUrlCount, iUpTimeSec, iDownloadTimeSec, - BoolToStr(bDownloadPaused), BoolToStr(bDownloadPaused), BoolToStr(bDownloadPaused), - BoolToStr(bServerStandBy), BoolToStr(bPostPaused), BoolToStr(bScanPaused), - iFreeDiskSpaceLo, iFreeDiskSpaceHi, iFreeDiskSpaceMB, iServerTime, iResumeTime, - BoolToStr(bFeedActive), iQueuedScripts); + remainingSizeLo, remainingSizeHi, remainingMBytes, forcedSizeLo, + forcedSizeHi, forcedMBytes, downloadedSizeLo, downloadedSizeHi, + downloadedMBytes, articleCacheLo, articleCacheHi, articleCacheMBytes, + downloadRate, averageDownloadRate, downloadLimit, threadCount, + postJobCount, postJobCount, urlCount, upTimeSec, downloadTimeSec, + BoolToStr(downloadPaused), BoolToStr(downloadPaused), BoolToStr(downloadPaused), + BoolToStr(serverStandBy), BoolToStr(postPaused), BoolToStr(scanPaused), + freeDiskSpaceLo, freeDiskSpaceHi, freeDiskSpaceMB, serverTime, resumeTime, + BoolToStr(feedActive), queuedScripts); int index = 0; for (Servers::iterator it = g_pServerPool->GetServers()->begin(); it != g_pServerPool->GetServers()->end(); it++) { - NewsServer* pServer = *it; + NewsServer* server = *it; AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_NEWSSERVER_ITEM : XML_NEWSSERVER_ITEM, - pServer->GetID(), BoolToStr(pServer->GetActive())); + server->GetID(), BoolToStr(server->GetActive())); } AppendResponse(IsJson() ? JSON_STATUS_END : XML_STATUS_END); @@ -1432,36 +1432,36 @@ void StatusXmlCommand::Execute() // struct[] log(idfrom, entries) void LogXmlCommand::Execute() { - m_iIDFrom = 0; - m_iNrEntries = 0; - if (!NextParamAsInt(&m_iIDFrom) || !NextParamAsInt(&m_iNrEntries) || (m_iNrEntries > 0 && m_iIDFrom > 0)) + m_idFrom = 0; + m_nrEntries = 0; + if (!NextParamAsInt(&m_idFrom) || !NextParamAsInt(&m_nrEntries) || (m_nrEntries > 0 && m_idFrom > 0)) { BuildErrorResponse(2, "Invalid parameter"); return; } - debug("iIDFrom=%i", m_iIDFrom); - debug("iNrEntries=%i", m_iNrEntries); + debug("iIDFrom=%i", m_idFrom); + debug("iNrEntries=%i", m_nrEntries); AppendResponse(IsJson() ? "[\n" : "\n"); - MessageList* pMessages = LockMessages(); + MessageList* messages = LockMessages(); - int iStart = pMessages->size(); - if (m_iNrEntries > 0) + int start = messages->size(); + if (m_nrEntries > 0) { - if (m_iNrEntries > (int)pMessages->size()) + if (m_nrEntries > (int)messages->size()) { - m_iNrEntries = pMessages->size(); + m_nrEntries = messages->size(); } - iStart = pMessages->size() - m_iNrEntries; + start = messages->size() - m_nrEntries; } - if (m_iIDFrom > 0 && !pMessages->empty()) + if (m_idFrom > 0 && !messages->empty()) { - m_iNrEntries = pMessages->size(); - iStart = m_iIDFrom - pMessages->front()->GetID(); - if (iStart < 0) + m_nrEntries = messages->size(); + start = m_idFrom - messages->front()->GetID(); + if (start < 0) { - iStart = 0; + start = 0; } } @@ -1481,19 +1481,19 @@ void LogXmlCommand::Execute() "\"Text\" : \"%s\"\n" "}"; - const char* szMessageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL" }; + const char* messageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL" }; int index = 0; - for (unsigned int i = (unsigned int)iStart; i < pMessages->size(); i++) + for (unsigned int i = (unsigned int)start; i < messages->size(); i++) { - Message* pMessage = (*pMessages)[i]; + Message* message = (*messages)[i]; - char* xmltext = EncodeStr(pMessage->GetText()); + char* xmltext = EncodeStr(message->GetText()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_LOG_ITEM : XML_LOG_ITEM, - pMessage->GetID(), szMessageType[pMessage->GetKind()], pMessage->GetTime(), xmltext); + message->GetID(), messageType[message->GetKind()], message->GetTime(), xmltext); free(xmltext); } @@ -1516,29 +1516,29 @@ void LogXmlCommand::UnlockMessages() // For backward compatibility with 0.8 parameter "NZBID" is optional void ListFilesXmlCommand::Execute() { - int iIDStart = 0; - int iIDEnd = 0; - if (NextParamAsInt(&iIDStart) && (!NextParamAsInt(&iIDEnd) || iIDEnd < iIDStart)) + int idStart = 0; + int idEnd = 0; + if (NextParamAsInt(&idStart) && (!NextParamAsInt(&idEnd) || idEnd < idStart)) { BuildErrorResponse(2, "Invalid parameter"); return; } // For backward compatibility with 0.8 parameter "NZBID" is optional (error checking omitted) - int iNZBID = 0; - NextParamAsInt(&iNZBID); + int nzbId = 0; + NextParamAsInt(&nzbId); - if (iNZBID > 0 && (iIDStart != 0 || iIDEnd != 0)) + if (nzbId > 0 && (idStart != 0 || idEnd != 0)) { BuildErrorResponse(2, "Invalid parameter"); return; } - debug("iIDStart=%i", iIDStart); - debug("iIDEnd=%i", iIDEnd); + debug("iIDStart=%i", idStart); + debug("iIDEnd=%i", idEnd); AppendResponse(IsJson() ? "[\n" : "\n"); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); const char* XML_LIST_ITEM = "\n" @@ -1588,37 +1588,37 @@ void ListFilesXmlCommand::Execute() int index = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - for (FileList::iterator it2 = pNZBInfo->GetFileList()->begin(); it2 != pNZBInfo->GetFileList()->end(); it2++) + NZBInfo* nzbInfo = *it; + for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { - FileInfo* pFileInfo = *it2; + FileInfo* fileInfo = *it2; - if ((iNZBID > 0 && iNZBID == pFileInfo->GetNZBInfo()->GetID()) || - (iNZBID == 0 && (iIDStart == 0 || (iIDStart <= pFileInfo->GetID() && pFileInfo->GetID() <= iIDEnd)))) + if ((nzbId > 0 && nzbId == fileInfo->GetNZBInfo()->GetID()) || + (nzbId == 0 && (idStart == 0 || (idStart <= fileInfo->GetID() && fileInfo->GetID() <= idEnd)))) { - unsigned long iFileSizeHi, iFileSizeLo; - unsigned long iRemainingSizeLo, iRemainingSizeHi; - Util::SplitInt64(pFileInfo->GetSize(), &iFileSizeHi, &iFileSizeLo); - Util::SplitInt64(pFileInfo->GetRemainingSize(), &iRemainingSizeHi, &iRemainingSizeLo); - char* xmlNZBFilename = EncodeStr(pFileInfo->GetNZBInfo()->GetFilename()); - char* xmlSubject = EncodeStr(pFileInfo->GetSubject()); - char* xmlFilename = EncodeStr(pFileInfo->GetFilename()); - char* xmlDestDir = EncodeStr(pFileInfo->GetNZBInfo()->GetDestDir()); - char* xmlCategory = EncodeStr(pFileInfo->GetNZBInfo()->GetCategory()); - char* xmlNZBNicename = EncodeStr(pFileInfo->GetNZBInfo()->GetName()); + unsigned long fileSizeHi, fileSizeLo; + unsigned long remainingSizeLo, remainingSizeHi; + Util::SplitInt64(fileInfo->GetSize(), &fileSizeHi, &fileSizeLo); + Util::SplitInt64(fileInfo->GetRemainingSize(), &remainingSizeHi, &remainingSizeLo); + char* xmlNZBFilename = EncodeStr(fileInfo->GetNZBInfo()->GetFilename()); + char* xmlSubject = EncodeStr(fileInfo->GetSubject()); + char* xmlFilename = EncodeStr(fileInfo->GetFilename()); + char* xmlDestDir = EncodeStr(fileInfo->GetNZBInfo()->GetDestDir()); + char* xmlCategory = EncodeStr(fileInfo->GetNZBInfo()->GetCategory()); + char* xmlNZBNicename = EncodeStr(fileInfo->GetNZBInfo()->GetName()); - int iProgress = pFileInfo->GetFailedSize() == 0 && pFileInfo->GetSuccessSize() == 0 ? 0 : - (int)(1000 - pFileInfo->GetRemainingSize() * 1000 / (pFileInfo->GetSize() - pFileInfo->GetMissedSize())); + int progress = fileInfo->GetFailedSize() == 0 && fileInfo->GetSuccessSize() == 0 ? 0 : + (int)(1000 - fileInfo->GetRemainingSize() * 1000 / (fileInfo->GetSize() - fileInfo->GetMissedSize())); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_LIST_ITEM : XML_LIST_ITEM, - pFileInfo->GetID(), iFileSizeLo, iFileSizeHi, iRemainingSizeLo, iRemainingSizeHi, - pFileInfo->GetTime(), BoolToStr(pFileInfo->GetFilenameConfirmed()), - BoolToStr(pFileInfo->GetPaused()), pFileInfo->GetNZBInfo()->GetID(), xmlNZBNicename, + fileInfo->GetID(), fileSizeLo, fileSizeHi, remainingSizeLo, remainingSizeHi, + fileInfo->GetTime(), BoolToStr(fileInfo->GetFilenameConfirmed()), + BoolToStr(fileInfo->GetPaused()), fileInfo->GetNZBInfo()->GetID(), xmlNZBNicename, xmlNZBNicename, xmlNZBFilename, xmlSubject, xmlFilename, xmlDestDir, xmlCategory, - pFileInfo->GetNZBInfo()->GetPriority(), pFileInfo->GetActiveDownloads(), iProgress); + fileInfo->GetNZBInfo()->GetPriority(), fileInfo->GetActiveDownloads(), progress); free(xmlNZBFilename); free(xmlSubject); @@ -1634,7 +1634,7 @@ void ListFilesXmlCommand::Execute() AppendResponse(IsJson() ? "\n]" : "\n"); } -void NzbInfoXmlCommand::AppendNZBInfoFields(NZBInfo* pNZBInfo) +void NzbInfoXmlCommand::AppendNZBInfoFields(NZBInfo* nzbInfo) { const char* XML_NZB_ITEM_START = "NZBID%i\n" @@ -1786,52 +1786,52 @@ void NzbInfoXmlCommand::AppendNZBInfoFields(NZBInfo* pNZBInfo) "\"FailedArticles\" : %i\n" "}"; - const char* szKindName[] = { "NZB", "URL" }; - const char* szParStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "REPAIR_POSSIBLE", "MANUAL" }; - const char* szUnpackStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "SPACE", "PASSWORD" }; - const char* szMoveStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; - const char* szScriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; - const char* szDeleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; - const char* szMarkStatusName[] = { "NONE", "BAD", "GOOD", "SUCCESS" }; - const char* szUrlStatusName[] = { "NONE", "UNKNOWN", "SUCCESS", "FAILURE", "UNKNOWN", "SCAN_SKIPPED", "SCAN_FAILURE" }; - const char* szDupeModeName[] = { "SCORE", "ALL", "FORCE" }; + const char* kindName[] = { "NZB", "URL" }; + const char* parStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "REPAIR_POSSIBLE", "MANUAL" }; + const char* unpackStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "SPACE", "PASSWORD" }; + const char* moveStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; + const char* scriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; + const char* deleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; + const char* markStatusName[] = { "NONE", "BAD", "GOOD", "SUCCESS" }; + const char* urlStatusName[] = { "NONE", "UNKNOWN", "SUCCESS", "FAILURE", "UNKNOWN", "SCAN_SKIPPED", "SCAN_FAILURE" }; + const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; - unsigned long iFileSizeHi, iFileSizeLo, iFileSizeMB; - Util::SplitInt64(pNZBInfo->GetSize(), &iFileSizeHi, &iFileSizeLo); - iFileSizeMB = (int)(pNZBInfo->GetSize() / 1024 / 1024); + unsigned long fileSizeHi, fileSizeLo, fileSizeMB; + Util::SplitInt64(nzbInfo->GetSize(), &fileSizeHi, &fileSizeLo); + fileSizeMB = (int)(nzbInfo->GetSize() / 1024 / 1024); - unsigned long iDownloadedSizeHi, iDownloadedSizeLo, iDownloadedSizeMB; - Util::SplitInt64(pNZBInfo->GetDownloadedSize(), &iDownloadedSizeHi, &iDownloadedSizeLo); - iDownloadedSizeMB = (int)(pNZBInfo->GetDownloadedSize() / 1024 / 1024); + unsigned long downloadedSizeHi, downloadedSizeLo, downloadedSizeMB; + Util::SplitInt64(nzbInfo->GetDownloadedSize(), &downloadedSizeHi, &downloadedSizeLo); + downloadedSizeMB = (int)(nzbInfo->GetDownloadedSize() / 1024 / 1024); - int iMessageCount = pNZBInfo->GetMessageCount() > 0 ? pNZBInfo->GetMessageCount() : pNZBInfo->GetCachedMessageCount(); + int messageCount = nzbInfo->GetMessageCount() > 0 ? nzbInfo->GetMessageCount() : nzbInfo->GetCachedMessageCount(); - char* xmlURL = EncodeStr(pNZBInfo->GetURL()); - char* xmlNZBFilename = EncodeStr(pNZBInfo->GetFilename()); - char* xmlNZBNicename = EncodeStr(pNZBInfo->GetName()); - char* xmlDestDir = EncodeStr(pNZBInfo->GetDestDir()); - char* xmlFinalDir = EncodeStr(pNZBInfo->GetFinalDir()); - char* xmlCategory = EncodeStr(pNZBInfo->GetCategory()); - char* xmlDupeKey = EncodeStr(pNZBInfo->GetDupeKey()); - const char* szExParStatus = pNZBInfo->GetExtraParBlocks() > 0 ? "RECIPIENT" : pNZBInfo->GetExtraParBlocks() < 0 ? "DONOR" : "NONE"; + char* xmlURL = EncodeStr(nzbInfo->GetURL()); + char* xmlNZBFilename = EncodeStr(nzbInfo->GetFilename()); + char* xmlNZBNicename = EncodeStr(nzbInfo->GetName()); + char* xmlDestDir = EncodeStr(nzbInfo->GetDestDir()); + char* xmlFinalDir = EncodeStr(nzbInfo->GetFinalDir()); + char* xmlCategory = EncodeStr(nzbInfo->GetCategory()); + char* xmlDupeKey = EncodeStr(nzbInfo->GetDupeKey()); + const char* exParStatus = nzbInfo->GetExtraParBlocks() > 0 ? "RECIPIENT" : nzbInfo->GetExtraParBlocks() < 0 ? "DONOR" : "NONE"; AppendFmtResponse(IsJson() ? JSON_NZB_ITEM_START : XML_NZB_ITEM_START, - pNZBInfo->GetID(), xmlNZBNicename, xmlNZBNicename, szKindName[pNZBInfo->GetKind()], + nzbInfo->GetID(), xmlNZBNicename, xmlNZBNicename, kindName[nzbInfo->GetKind()], xmlURL, xmlNZBFilename, xmlDestDir, xmlFinalDir, xmlCategory, - szParStatusName[pNZBInfo->GetParStatus()], szExParStatus, - szUnpackStatusName[pNZBInfo->GetUnpackStatus()], szMoveStatusName[pNZBInfo->GetMoveStatus()], - szScriptStatusName[pNZBInfo->GetScriptStatuses()->CalcTotalStatus()], - szDeleteStatusName[pNZBInfo->GetDeleteStatus()], szMarkStatusName[pNZBInfo->GetMarkStatus()], - szUrlStatusName[pNZBInfo->GetUrlStatus()], - iFileSizeLo, iFileSizeHi, iFileSizeMB, pNZBInfo->GetFileCount(), - pNZBInfo->GetMinTime(), pNZBInfo->GetMaxTime(), - pNZBInfo->GetTotalArticles(), pNZBInfo->GetCurrentSuccessArticles(), pNZBInfo->GetCurrentFailedArticles(), - pNZBInfo->CalcHealth(), pNZBInfo->CalcCriticalHealth(false), - xmlDupeKey, pNZBInfo->GetDupeScore(), szDupeModeName[pNZBInfo->GetDupeMode()], - BoolToStr(pNZBInfo->GetDeleteStatus() != NZBInfo::dsNone), - iDownloadedSizeLo, iDownloadedSizeHi, iDownloadedSizeMB, pNZBInfo->GetDownloadSec(), - pNZBInfo->GetPostInfo() && pNZBInfo->GetPostInfo()->GetStartTime() ? time(NULL) - pNZBInfo->GetPostInfo()->GetStartTime() : pNZBInfo->GetPostTotalSec(), - pNZBInfo->GetParSec(), pNZBInfo->GetRepairSec(), pNZBInfo->GetUnpackSec(), iMessageCount, pNZBInfo->GetExtraParBlocks()); + parStatusName[nzbInfo->GetParStatus()], exParStatus, + unpackStatusName[nzbInfo->GetUnpackStatus()], moveStatusName[nzbInfo->GetMoveStatus()], + scriptStatusName[nzbInfo->GetScriptStatuses()->CalcTotalStatus()], + deleteStatusName[nzbInfo->GetDeleteStatus()], markStatusName[nzbInfo->GetMarkStatus()], + urlStatusName[nzbInfo->GetUrlStatus()], + fileSizeLo, fileSizeHi, fileSizeMB, nzbInfo->GetFileCount(), + nzbInfo->GetMinTime(), nzbInfo->GetMaxTime(), + nzbInfo->GetTotalArticles(), nzbInfo->GetCurrentSuccessArticles(), nzbInfo->GetCurrentFailedArticles(), + nzbInfo->CalcHealth(), nzbInfo->CalcCriticalHealth(false), + xmlDupeKey, nzbInfo->GetDupeScore(), dupeModeName[nzbInfo->GetDupeMode()], + BoolToStr(nzbInfo->GetDeleteStatus() != NZBInfo::dsNone), + downloadedSizeLo, downloadedSizeHi, downloadedSizeMB, nzbInfo->GetDownloadSec(), + nzbInfo->GetPostInfo() && nzbInfo->GetPostInfo()->GetStartTime() ? time(NULL) - nzbInfo->GetPostInfo()->GetStartTime() : nzbInfo->GetPostTotalSec(), + nzbInfo->GetParSec(), nzbInfo->GetRepairSec(), nzbInfo->GetUnpackSec(), messageCount, nzbInfo->GetExtraParBlocks()); free(xmlURL); free(xmlNZBNicename); @@ -1842,15 +1842,15 @@ void NzbInfoXmlCommand::AppendNZBInfoFields(NZBInfo* pNZBInfo) free(xmlDupeKey); // Post-processing parameters - int iParamIndex = 0; - for (NZBParameterList::iterator it = pNZBInfo->GetParameters()->begin(); it != pNZBInfo->GetParameters()->end(); it++) + int paramIndex = 0; + for (NZBParameterList::iterator it = nzbInfo->GetParameters()->begin(); it != nzbInfo->GetParameters()->end(); it++) { - NZBParameter* pParameter = *it; + NZBParameter* parameter = *it; - char* xmlName = EncodeStr(pParameter->GetName()); - char* xmlValue = EncodeStr(pParameter->GetValue()); + char* xmlName = EncodeStr(parameter->GetName()); + char* xmlValue = EncodeStr(parameter->GetValue()); - AppendCondResponse(",\n", IsJson() && iParamIndex++ > 0); + AppendCondResponse(",\n", IsJson() && paramIndex++ > 0); AppendFmtResponse(IsJson() ? JSON_PARAMETER_ITEM : XML_PARAMETER_ITEM, xmlName, xmlValue); free(xmlName); @@ -1860,15 +1860,15 @@ void NzbInfoXmlCommand::AppendNZBInfoFields(NZBInfo* pNZBInfo) AppendResponse(IsJson() ? JSON_NZB_ITEM_SCRIPT_START : XML_NZB_ITEM_SCRIPT_START); // Script statuses - int iScriptIndex = 0; - for (ScriptStatusList::iterator it = pNZBInfo->GetScriptStatuses()->begin(); it != pNZBInfo->GetScriptStatuses()->end(); it++) + int scriptIndex = 0; + for (ScriptStatusList::iterator it = nzbInfo->GetScriptStatuses()->begin(); it != nzbInfo->GetScriptStatuses()->end(); it++) { - ScriptStatus* pScriptStatus = *it; + ScriptStatus* scriptStatus = *it; - char* xmlName = EncodeStr(pScriptStatus->GetName()); - char* xmlStatus = EncodeStr(szScriptStatusName[pScriptStatus->GetStatus()]); + char* xmlName = EncodeStr(scriptStatus->GetName()); + char* xmlStatus = EncodeStr(scriptStatusName[scriptStatus->GetStatus()]); - AppendCondResponse(",\n", IsJson() && iScriptIndex++ > 0); + AppendCondResponse(",\n", IsJson() && scriptIndex++ > 0); AppendFmtResponse(IsJson() ? JSON_SCRIPT_ITEM : XML_SCRIPT_ITEM, xmlName, xmlStatus); free(xmlName); @@ -1878,20 +1878,20 @@ void NzbInfoXmlCommand::AppendNZBInfoFields(NZBInfo* pNZBInfo) AppendResponse(IsJson() ? JSON_NZB_ITEM_STATS_START : XML_NZB_ITEM_STATS_START); // Server stats - int iStatIndex = 0; - for (ServerStatList::iterator it = pNZBInfo->GetCurrentServerStats()->begin(); it != pNZBInfo->GetCurrentServerStats()->end(); it++) + int statIndex = 0; + for (ServerStatList::iterator it = nzbInfo->GetCurrentServerStats()->begin(); it != nzbInfo->GetCurrentServerStats()->end(); it++) { - ServerStat* pServerStat = *it; + ServerStat* serverStat = *it; - AppendCondResponse(",\n", IsJson() && iStatIndex++ > 0); + AppendCondResponse(",\n", IsJson() && statIndex++ > 0); AppendFmtResponse(IsJson() ? JSON_STAT_ITEM : XML_STAT_ITEM, - pServerStat->GetServerID(), pServerStat->GetSuccessArticles(), pServerStat->GetFailedArticles()); + serverStat->GetServerID(), serverStat->GetSuccessArticles(), serverStat->GetFailedArticles()); } AppendResponse(IsJson() ? JSON_NZB_ITEM_END : XML_NZB_ITEM_END); } -void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* pPostInfo, int iLogEntries, bool bPostQueue) +void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* postInfo, int logEntries, bool postQueue) { const char* XML_GROUPQUEUE_ITEM_START = "PostInfoText%s\n" @@ -1944,55 +1944,55 @@ void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* pPostInfo, int iLogEntrie "\"Text\" : \"%s\"\n" "}"; - const char* szMessageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL"}; + const char* messageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL"}; - const char* szItemStart = bPostQueue ? IsJson() ? JSON_POSTQUEUE_ITEM_START : XML_POSTQUEUE_ITEM_START : + const char* itemStart = postQueue ? IsJson() ? JSON_POSTQUEUE_ITEM_START : XML_POSTQUEUE_ITEM_START : IsJson() ? JSON_GROUPQUEUE_ITEM_START : XML_GROUPQUEUE_ITEM_START; - if (pPostInfo) + if (postInfo) { - time_t tCurTime = time(NULL); - char* xmlProgressLabel = EncodeStr(pPostInfo->GetProgressLabel()); + time_t curTime = time(NULL); + char* xmlProgressLabel = EncodeStr(postInfo->GetProgressLabel()); - AppendFmtResponse(szItemStart, xmlProgressLabel, pPostInfo->GetStageProgress(), - pPostInfo->GetStageTime() ? tCurTime - pPostInfo->GetStageTime() : 0, - pPostInfo->GetStartTime() ? tCurTime - pPostInfo->GetStartTime() : 0); + AppendFmtResponse(itemStart, xmlProgressLabel, postInfo->GetStageProgress(), + postInfo->GetStageTime() ? curTime - postInfo->GetStageTime() : 0, + postInfo->GetStartTime() ? curTime - postInfo->GetStartTime() : 0); free(xmlProgressLabel); } else { - AppendFmtResponse(szItemStart, "NONE", "", 0, 0, 0, 0); + AppendFmtResponse(itemStart, "NONE", "", 0, 0, 0, 0); } AppendResponse(IsJson() ? JSON_LOG_START : XML_LOG_START); - if (iLogEntries > 0 && pPostInfo) + if (logEntries > 0 && postInfo) { - MessageList* pMessages = pPostInfo->GetNZBInfo()->LockCachedMessages(); - if (!pMessages->empty()) + MessageList* messages = postInfo->GetNZBInfo()->LockCachedMessages(); + if (!messages->empty()) { - if (iLogEntries > (int)pMessages->size()) + if (logEntries > (int)messages->size()) { - iLogEntries = pMessages->size(); + logEntries = messages->size(); } - int iStart = pMessages->size() - iLogEntries; + int start = messages->size() - logEntries; int index = 0; - for (unsigned int i = (unsigned int)iStart; i < pMessages->size(); i++) + for (unsigned int i = (unsigned int)start; i < messages->size(); i++) { - Message* pMessage = (*pMessages)[i]; + Message* message = (*messages)[i]; - char* xmltext = EncodeStr(pMessage->GetText()); + char* xmltext = EncodeStr(message->GetText()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_LOG_ITEM : XML_LOG_ITEM, - pMessage->GetID(), szMessageType[pMessage->GetKind()], pMessage->GetTime(), xmltext); + message->GetID(), messageType[message->GetKind()], message->GetTime(), xmltext); free(xmltext); } } - pPostInfo->GetNZBInfo()->UnlockCachedMessages(); + postInfo->GetNZBInfo()->UnlockCachedMessages(); } AppendResponse(IsJson() ? JSON_POSTQUEUE_ITEM_END : XML_POSTQUEUE_ITEM_END); @@ -2001,8 +2001,8 @@ void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* pPostInfo, int iLogEntrie // struct[] listgroups(int NumberOfLogEntries) void ListGroupsXmlCommand::Execute() { - int iNrEntries = 0; - NextParamAsInt(&iNrEntries); + int nrEntries = 0; + NextParamAsInt(&nrEntries); AppendResponse(IsJson() ? "[\n" : "\n"); @@ -2048,36 +2048,36 @@ void ListGroupsXmlCommand::Execute() int index = 0; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; + NZBInfo* nzbInfo = *it; - unsigned long iRemainingSizeLo, iRemainingSizeHi, iRemainingSizeMB; - unsigned long iPausedSizeLo, iPausedSizeHi, iPausedSizeMB; - Util::SplitInt64(pNZBInfo->GetRemainingSize(), &iRemainingSizeHi, &iRemainingSizeLo); - iRemainingSizeMB = (int)(pNZBInfo->GetRemainingSize() / 1024 / 1024); - Util::SplitInt64(pNZBInfo->GetPausedSize(), &iPausedSizeHi, &iPausedSizeLo); - iPausedSizeMB = (int)(pNZBInfo->GetPausedSize() / 1024 / 1024); - const char* szStatus = DetectStatus(pNZBInfo); + unsigned long remainingSizeLo, remainingSizeHi, remainingSizeMB; + unsigned long pausedSizeLo, pausedSizeHi, pausedSizeMB; + Util::SplitInt64(nzbInfo->GetRemainingSize(), &remainingSizeHi, &remainingSizeLo); + remainingSizeMB = (int)(nzbInfo->GetRemainingSize() / 1024 / 1024); + Util::SplitInt64(nzbInfo->GetPausedSize(), &pausedSizeHi, &pausedSizeLo); + pausedSizeMB = (int)(nzbInfo->GetPausedSize() / 1024 / 1024); + const char* status = DetectStatus(nzbInfo); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_LIST_ITEM_START : XML_LIST_ITEM_START, - pNZBInfo->GetID(), pNZBInfo->GetID(), iRemainingSizeLo, iRemainingSizeHi, iRemainingSizeMB, - iPausedSizeLo, iPausedSizeHi, iPausedSizeMB, (int)pNZBInfo->GetFileList()->size(), - pNZBInfo->GetRemainingParCount(), pNZBInfo->GetPriority(), pNZBInfo->GetPriority(), - pNZBInfo->GetActiveDownloads(), szStatus); + nzbInfo->GetID(), nzbInfo->GetID(), remainingSizeLo, remainingSizeHi, remainingSizeMB, + pausedSizeLo, pausedSizeHi, pausedSizeMB, (int)nzbInfo->GetFileList()->size(), + nzbInfo->GetRemainingParCount(), nzbInfo->GetPriority(), nzbInfo->GetPriority(), + nzbInfo->GetActiveDownloads(), status); - AppendNZBInfoFields(pNZBInfo); + AppendNZBInfoFields(nzbInfo); AppendCondResponse(",\n", IsJson()); - AppendPostInfoFields(pNZBInfo->GetPostInfo(), iNrEntries, false); + AppendPostInfoFields(nzbInfo->GetPostInfo(), nrEntries, false); AppendResponse(IsJson() ? JSON_LIST_ITEM_END : XML_LIST_ITEM_END); - if (it == pDownloadQueue->GetQueue()->begin()) + if (it == downloadQueue->GetQueue()->begin()) { - OptimizeResponse(pDownloadQueue->GetQueue()->size()); + OptimizeResponse(downloadQueue->GetQueue()->size()); } } @@ -2086,45 +2086,45 @@ void ListGroupsXmlCommand::Execute() AppendResponse(IsJson() ? "\n]" : "\n"); } -const char* ListGroupsXmlCommand::DetectStatus(NZBInfo* pNZBInfo) +const char* ListGroupsXmlCommand::DetectStatus(NZBInfo* nzbInfo) { - const char* szPostStageName[] = { "PP_QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "PP_FINISHED" }; + const char* postStageName[] = { "PP_QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "PP_FINISHED" }; - const char* szStatus = NULL; + const char* status = NULL; - if (pNZBInfo->GetPostInfo()) + if (nzbInfo->GetPostInfo()) { - bool bQueueScriptActive = false; - if (pNZBInfo->GetPostInfo()->GetStage() == PostInfo::ptQueued && - g_pQueueScriptCoordinator->HasJob(pNZBInfo->GetID(), &bQueueScriptActive)) + bool queueScriptActive = false; + if (nzbInfo->GetPostInfo()->GetStage() == PostInfo::ptQueued && + g_pQueueScriptCoordinator->HasJob(nzbInfo->GetID(), &queueScriptActive)) { - szStatus = bQueueScriptActive ? "QS_EXECUTING" : "QS_QUEUED"; + status = queueScriptActive ? "QS_EXECUTING" : "QS_QUEUED"; } else { - szStatus = szPostStageName[pNZBInfo->GetPostInfo()->GetStage()]; + status = postStageName[nzbInfo->GetPostInfo()->GetStage()]; } } - else if (pNZBInfo->GetActiveDownloads() > 0) + else if (nzbInfo->GetActiveDownloads() > 0) { - szStatus = pNZBInfo->GetKind() == NZBInfo::nkUrl ? "FETCHING" : "DOWNLOADING"; + status = nzbInfo->GetKind() == NZBInfo::nkUrl ? "FETCHING" : "DOWNLOADING"; } - else if ((pNZBInfo->GetPausedSize() > 0) && (pNZBInfo->GetRemainingSize() == pNZBInfo->GetPausedSize())) + else if ((nzbInfo->GetPausedSize() > 0) && (nzbInfo->GetRemainingSize() == nzbInfo->GetPausedSize())) { - szStatus = "PAUSED"; + status = "PAUSED"; } else { - szStatus = "QUEUED"; + status = "QUEUED"; } - return szStatus; + return status; } typedef struct { - int iActionID; - const char* szActionName; + int actionId; + const char* actionName; } EditCommandEntry; EditCommandEntry EditCommandNameMap[] = { @@ -2184,59 +2184,59 @@ void EditQueueXmlCommand::Execute() return; } - char* szEditCommand; - if (!NextParamAsStr(&szEditCommand)) + char* editCommand; + if (!NextParamAsStr(&editCommand)) { BuildErrorResponse(2, "Invalid parameter"); return; } - debug("EditCommand=%s", szEditCommand); + debug("EditCommand=%s", editCommand); - int iAction = -1; - for (int i = 0; const char* szName = EditCommandNameMap[i].szActionName; i++) + int action = -1; + for (int i = 0; const char* name = EditCommandNameMap[i].actionName; i++) { - if (!strcasecmp(szEditCommand, szName)) + if (!strcasecmp(editCommand, name)) { - iAction = EditCommandNameMap[i].iActionID; + action = EditCommandNameMap[i].actionId; break; } } - if (iAction == -1) + if (action == -1) { BuildErrorResponse(3, "Invalid action"); return; } - int iOffset = 0; - if (!NextParamAsInt(&iOffset)) + int offset = 0; + if (!NextParamAsInt(&offset)) { BuildErrorResponse(2, "Invalid parameter"); return; } - char* szEditText; - if (!NextParamAsStr(&szEditText)) + char* editText; + if (!NextParamAsStr(&editText)) { BuildErrorResponse(2, "Invalid parameter"); return; } - debug("EditText=%s", szEditText); + debug("EditText=%s", editText); - DecodeStr(szEditText); + DecodeStr(editText); IDList cIDList; - int iID = 0; - while (NextParamAsInt(&iID)) + int id = 0; + while (NextParamAsInt(&id)) { - cIDList.push_back(iID); + cIDList.push_back(id); } - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - bool bOK = pDownloadQueue->EditList(&cIDList, NULL, DownloadQueue::mmID, (DownloadQueue::EEditAction)iAction, iOffset, szEditText); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + bool ok = downloadQueue->EditList(&cIDList, NULL, DownloadQueue::mmID, (DownloadQueue::EEditAction)action, offset, editText); DownloadQueue::Unlock(); - BuildBoolResponse(bOK); + BuildBoolResponse(ok); } // v16: @@ -2252,129 +2252,129 @@ void DownloadXmlCommand::Execute() return; } - bool bV13 = true; + bool v13 = true; - char* szNZBFilename; - if (!NextParamAsStr(&szNZBFilename)) + char* nzbFilename; + if (!NextParamAsStr(&nzbFilename)) { BuildErrorResponse(2, "Invalid parameter (NZBFileName)"); return; } - char* szNZBContent; - if (!NextParamAsStr(&szNZBContent)) + char* nzbContent; + if (!NextParamAsStr(&nzbContent)) { BuildErrorResponse(2, "Invalid parameter (NZBContent)"); return; } - char* szCategory; - if (!NextParamAsStr(&szCategory)) + char* category; + if (!NextParamAsStr(&category)) { - bV13 = false; - szCategory = szNZBContent; + v13 = false; + category = nzbContent; } - DecodeStr(szNZBFilename); - DecodeStr(szCategory); + DecodeStr(nzbFilename); + DecodeStr(category); - debug("FileName=%s", szNZBFilename); + debug("FileName=%s", nzbFilename); // For backward compatibility with 0.8 parameter "Priority" is optional (error checking omitted) - int iPriority = 0; - NextParamAsInt(&iPriority); + int priority = 0; + NextParamAsInt(&priority); - bool bAddTop; - if (!NextParamAsBool(&bAddTop)) + bool addTop; + if (!NextParamAsBool(&addTop)) { BuildErrorResponse(2, "Invalid parameter (AddTop)"); return; } - if (!bV13 && !NextParamAsStr(&szNZBContent)) + if (!v13 && !NextParamAsStr(&nzbContent)) { BuildErrorResponse(2, "Invalid parameter (FileContent)"); return; } - DecodeStr(szNZBContent); + DecodeStr(nzbContent); - bool bAddPaused = false; - char* szDupeKey = NULL; - int iDupeScore = 0; - EDupeMode eDupeMode = dmScore; - if (NextParamAsBool(&bAddPaused)) + bool addPaused = false; + char* dupeKey = NULL; + int dupeScore = 0; + EDupeMode dupeMode = dmScore; + if (NextParamAsBool(&addPaused)) { - if (!NextParamAsStr(&szDupeKey)) + if (!NextParamAsStr(&dupeKey)) { BuildErrorResponse(2, "Invalid parameter (DupeKey)"); return; } - DecodeStr(szDupeKey); - if (!NextParamAsInt(&iDupeScore)) + DecodeStr(dupeKey); + if (!NextParamAsInt(&dupeScore)) { BuildErrorResponse(2, "Invalid parameter (DupeScore)"); return; } - char* szDupeMode = NULL; - if (!NextParamAsStr(&szDupeMode) || - (strcasecmp(szDupeMode, "score") && strcasecmp(szDupeMode, "all") && strcasecmp(szDupeMode, "force"))) + char* dupeModeStr = NULL; + if (!NextParamAsStr(&dupeModeStr) || + (strcasecmp(dupeModeStr, "score") && strcasecmp(dupeModeStr, "all") && strcasecmp(dupeModeStr, "force"))) { BuildErrorResponse(2, "Invalid parameter (DupeMode)"); return; } - eDupeMode = !strcasecmp(szDupeMode, "all") ? dmAll : - !strcasecmp(szDupeMode, "force") ? dmForce : dmScore; + dupeMode = !strcasecmp(dupeModeStr, "all") ? dmAll : + !strcasecmp(dupeModeStr, "force") ? dmForce : dmScore; } - else if (bV13) + else if (v13) { BuildErrorResponse(2, "Invalid parameter (AddPaused)"); return; } NZBParameterList Params; - if (bV13) + if (v13) { - char* szParamName = NULL; - char* szParamValue = NULL; - while (NextParamAsStr(&szParamName)) + char* paramName = NULL; + char* paramValue = NULL; + while (NextParamAsStr(¶mName)) { - if (!NextParamAsStr(&szParamValue)) + if (!NextParamAsStr(¶mValue)) { BuildErrorResponse(2, "Invalid parameter (Parameters)"); return; } - Params.SetParameter(szParamName, szParamValue); + Params.SetParameter(paramName, paramValue); } } - if (!strncasecmp(szNZBContent, "http://", 6) || !strncasecmp(szNZBContent, "https://", 7)) + if (!strncasecmp(nzbContent, "http://", 6) || !strncasecmp(nzbContent, "https://", 7)) { // add url - NZBInfo* pNZBInfo = new NZBInfo(); - pNZBInfo->SetKind(NZBInfo::nkUrl); - pNZBInfo->SetURL(szNZBContent); - pNZBInfo->SetFilename(szNZBFilename); - pNZBInfo->SetCategory(szCategory); - pNZBInfo->SetPriority(iPriority); - pNZBInfo->SetAddUrlPaused(bAddPaused); - pNZBInfo->SetDupeKey(szDupeKey ? szDupeKey : ""); - pNZBInfo->SetDupeScore(iDupeScore); - pNZBInfo->SetDupeMode(eDupeMode); - pNZBInfo->GetParameters()->CopyFrom(&Params); - int iNZBID = pNZBInfo->GetID(); + NZBInfo* nzbInfo = new NZBInfo(); + nzbInfo->SetKind(NZBInfo::nkUrl); + nzbInfo->SetURL(nzbContent); + nzbInfo->SetFilename(nzbFilename); + nzbInfo->SetCategory(category); + nzbInfo->SetPriority(priority); + nzbInfo->SetAddUrlPaused(addPaused); + nzbInfo->SetDupeKey(dupeKey ? dupeKey : ""); + nzbInfo->SetDupeScore(dupeScore); + nzbInfo->SetDupeMode(dupeMode); + nzbInfo->GetParameters()->CopyFrom(&Params); + int nzbId = nzbInfo->GetID(); - char szNicename[1024]; - pNZBInfo->MakeNiceUrlName(szNZBContent, szNZBFilename, szNicename, sizeof(szNicename)); - info("Queue %s", szNicename); + char nicename[1024]; + nzbInfo->MakeNiceUrlName(nzbContent, nzbFilename, nicename, sizeof(nicename)); + info("Queue %s", nicename); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - pDownloadQueue->GetQueue()->Add(pNZBInfo, bAddTop); - pDownloadQueue->Save(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + downloadQueue->GetQueue()->Add(nzbInfo, addTop); + downloadQueue->Save(); DownloadQueue::Unlock(); - if (bV13) + if (v13) { - BuildIntResponse(iNZBID); + BuildIntResponse(nzbId); } else { @@ -2384,22 +2384,22 @@ void DownloadXmlCommand::Execute() else { // add file content - int iLen = WebUtil::DecodeBase64(szNZBContent, 0, szNZBContent); - szNZBContent[iLen] = '\0'; + int len = WebUtil::DecodeBase64(nzbContent, 0, nzbContent); + nzbContent[len] = '\0'; //debug("FileContent=%s", szFileContent); - int iNZBID = -1; - g_pScanner->AddExternalFile(szNZBFilename, szCategory, iPriority, - szDupeKey, iDupeScore, eDupeMode, Params.empty() ? NULL : &Params, bAddTop, bAddPaused, NULL, - NULL, szNZBContent, iLen, &iNZBID); + int nzbId = -1; + g_pScanner->AddExternalFile(nzbFilename, category, priority, + dupeKey, dupeScore, dupeMode, Params.empty() ? NULL : &Params, addTop, addPaused, NULL, + NULL, nzbContent, len, &nzbId); - if (bV13) + if (v13) { - BuildIntResponse(iNZBID); + BuildIntResponse(nzbId); } else { - BuildBoolResponse(iNZBID > 0); + BuildBoolResponse(nzbId > 0); } } } @@ -2407,8 +2407,8 @@ void DownloadXmlCommand::Execute() // deprecated void PostQueueXmlCommand::Execute() { - int iNrEntries = 0; - NextParamAsInt(&iNrEntries); + int nrEntries = 0; + NextParamAsInt(&nrEntries); AppendResponse(IsJson() ? "[\n" : "\n"); @@ -2434,32 +2434,32 @@ void PostQueueXmlCommand::Execute() const char* JSON_POSTQUEUE_ITEM_END = "}"; - const char* szPostStageName[] = { "QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "FINISHED" }; + const char* postStageName[] = { "QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "FINISHED" }; - NZBList* pNZBList = DownloadQueue::Lock()->GetQueue(); + NZBList* nzbList = DownloadQueue::Lock()->GetQueue(); int index = 0; - for (NZBList::iterator it = pNZBList->begin(); it != pNZBList->end(); it++) + for (NZBList::iterator it = nzbList->begin(); it != nzbList->end(); it++) { - NZBInfo* pNZBInfo = *it; - PostInfo* pPostInfo = pNZBInfo->GetPostInfo(); - if (!pPostInfo) + NZBInfo* nzbInfo = *it; + PostInfo* postInfo = nzbInfo->GetPostInfo(); + if (!postInfo) { continue; } - char* xmlInfoName = EncodeStr(pPostInfo->GetNZBInfo()->GetName()); + char* xmlInfoName = EncodeStr(postInfo->GetNZBInfo()->GetName()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_POSTQUEUE_ITEM_START : XML_POSTQUEUE_ITEM_START, - pNZBInfo->GetID(), xmlInfoName, szPostStageName[pPostInfo->GetStage()], pPostInfo->GetFileProgress()); + nzbInfo->GetID(), xmlInfoName, postStageName[postInfo->GetStage()], postInfo->GetFileProgress()); free(xmlInfoName); - AppendNZBInfoFields(pPostInfo->GetNZBInfo()); + AppendNZBInfoFields(postInfo->GetNZBInfo()); AppendCondResponse(",\n", IsJson()); - AppendPostInfoFields(pPostInfo, iNrEntries, true); + AppendPostInfoFields(postInfo, nrEntries, true); AppendResponse(IsJson() ? JSON_POSTQUEUE_ITEM_END : XML_POSTQUEUE_ITEM_END); } @@ -2476,37 +2476,37 @@ void WriteLogXmlCommand::Execute() return; } - char* szKind; - char* szText; - if (!NextParamAsStr(&szKind) || !NextParamAsStr(&szText)) + char* kind; + char* text; + if (!NextParamAsStr(&kind) || !NextParamAsStr(&text)) { BuildErrorResponse(2, "Invalid parameter"); return; } - DecodeStr(szText); + DecodeStr(text); - debug("Kind=%s, Text=%s", szKind, szText); + debug("Kind=%s, Text=%s", kind, text); - if (!strcmp(szKind, "INFO")) + if (!strcmp(kind, "INFO")) { - info(szText); + info(text); } - else if (!strcmp(szKind, "WARNING")) + else if (!strcmp(kind, "WARNING")) { - warn(szText); + warn(text); } - else if (!strcmp(szKind, "ERROR")) + else if (!strcmp(kind, "ERROR")) { - error(szText); + error(text); } - else if (!strcmp(szKind, "DETAIL")) + else if (!strcmp(kind, "DETAIL")) { - detail(szText); + detail(text); } - else if (!strcmp(szKind, "DEBUG")) + else if (!strcmp(kind, "DEBUG")) { - debug(szText); + debug(text); } else { @@ -2536,11 +2536,11 @@ void ScanXmlCommand::Execute() return; } - bool bSyncMode = false; + bool syncMode = false; // optional parameter "SyncMode" - NextParamAsBool(&bSyncMode); + NextParamAsBool(&syncMode); - g_pScanner->ScanNZBDir(bSyncMode); + g_pScanner->ScanNZBDir(syncMode); BuildBoolResponse(true); } @@ -2606,74 +2606,74 @@ void HistoryXmlCommand::Execute() "\"DupStatus\" : \"%s\",\n" "\"Status\" : \"%s\"\n"; - const char* szDupStatusName[] = { "UNKNOWN", "SUCCESS", "FAILURE", "DELETED", "DUPE", "BAD", "GOOD" }; - const char* szDupeModeName[] = { "SCORE", "ALL", "FORCE" }; + const char* dupStatusName[] = { "UNKNOWN", "SUCCESS", "FAILURE", "DELETED", "DUPE", "BAD", "GOOD" }; + const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; - bool bDup = false; - NextParamAsBool(&bDup); + bool dup = false; + NextParamAsBool(&dup); - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); int index = 0; - for (HistoryList::iterator it = pDownloadQueue->GetHistory()->begin(); it != pDownloadQueue->GetHistory()->end(); it++) + for (HistoryList::iterator it = downloadQueue->GetHistory()->begin(); it != downloadQueue->GetHistory()->end(); it++) { - HistoryInfo* pHistoryInfo = *it; + HistoryInfo* historyInfo = *it; - if (pHistoryInfo->GetKind() == HistoryInfo::hkDup && !bDup) + if (historyInfo->GetKind() == HistoryInfo::hkDup && !dup) { continue; } - NZBInfo* pNZBInfo = NULL; - char szNicename[1024]; - pHistoryInfo->GetName(szNicename, sizeof(szNicename)); + NZBInfo* nzbInfo = NULL; + char nicename[1024]; + historyInfo->GetName(nicename, sizeof(nicename)); - char *xmlNicename = EncodeStr(szNicename); - const char* szStatus = DetectStatus(pHistoryInfo); + char *xmlNicename = EncodeStr(nicename); + const char* status = DetectStatus(historyInfo); AppendCondResponse(",\n", IsJson() && index++ > 0); - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb || - pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkNzb || + historyInfo->GetKind() == HistoryInfo::hkUrl) { - pNZBInfo = pHistoryInfo->GetNZBInfo(); + nzbInfo = historyInfo->GetNZBInfo(); AppendFmtResponse(IsJson() ? JSON_HISTORY_ITEM_START : XML_HISTORY_ITEM_START, - pHistoryInfo->GetID(), xmlNicename, pNZBInfo->GetParkedFileCount(), - pHistoryInfo->GetTime(), szStatus); + historyInfo->GetID(), xmlNicename, nzbInfo->GetParkedFileCount(), + historyInfo->GetTime(), status); } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkDup) + else if (historyInfo->GetKind() == HistoryInfo::hkDup) { - DupInfo* pDupInfo = pHistoryInfo->GetDupInfo(); + DupInfo* dupInfo = historyInfo->GetDupInfo(); - unsigned long iFileSizeHi, iFileSizeLo, iFileSizeMB; - Util::SplitInt64(pDupInfo->GetSize(), &iFileSizeHi, &iFileSizeLo); - iFileSizeMB = (int)(pDupInfo->GetSize() / 1024 / 1024); + unsigned long fileSizeHi, fileSizeLo, fileSizeMB; + Util::SplitInt64(dupInfo->GetSize(), &fileSizeHi, &fileSizeLo); + fileSizeMB = (int)(dupInfo->GetSize() / 1024 / 1024); - char* xmlDupeKey = EncodeStr(pDupInfo->GetDupeKey()); + char* xmlDupeKey = EncodeStr(dupInfo->GetDupeKey()); AppendFmtResponse(IsJson() ? JSON_HISTORY_DUP_ITEM : XML_HISTORY_DUP_ITEM, - pHistoryInfo->GetID(), pHistoryInfo->GetID(), "DUP", xmlNicename, pHistoryInfo->GetTime(), - iFileSizeLo, iFileSizeHi, iFileSizeMB, xmlDupeKey, pDupInfo->GetDupeScore(), - szDupeModeName[pDupInfo->GetDupeMode()], szDupStatusName[pDupInfo->GetStatus()], - szStatus); + historyInfo->GetID(), historyInfo->GetID(), "DUP", xmlNicename, historyInfo->GetTime(), + fileSizeLo, fileSizeHi, fileSizeMB, xmlDupeKey, dupInfo->GetDupeScore(), + dupeModeName[dupInfo->GetDupeMode()], dupStatusName[dupInfo->GetStatus()], + status); free(xmlDupeKey); } free(xmlNicename); - if (pNZBInfo) + if (nzbInfo) { - AppendNZBInfoFields(pNZBInfo); + AppendNZBInfoFields(nzbInfo); } AppendResponse(IsJson() ? JSON_HISTORY_ITEM_END : XML_HISTORY_ITEM_END); - if (it == pDownloadQueue->GetHistory()->begin()) + if (it == downloadQueue->GetHistory()->begin()) { - OptimizeResponse(pDownloadQueue->GetHistory()->size()); + OptimizeResponse(downloadQueue->GetHistory()->size()); } } @@ -2682,24 +2682,24 @@ void HistoryXmlCommand::Execute() DownloadQueue::Unlock(); } -const char* HistoryXmlCommand::DetectStatus(HistoryInfo* pHistoryInfo) +const char* HistoryXmlCommand::DetectStatus(HistoryInfo* historyInfo) { - const char* szStatus = "FAILURE/INTERNAL_ERROR"; + const char* status = "FAILURE/INTERNAL_ERROR"; - if (pHistoryInfo->GetKind() == HistoryInfo::hkNzb || pHistoryInfo->GetKind() == HistoryInfo::hkUrl) + if (historyInfo->GetKind() == HistoryInfo::hkNzb || historyInfo->GetKind() == HistoryInfo::hkUrl) { - NZBInfo* pNZBInfo = pHistoryInfo->GetNZBInfo(); - szStatus = pNZBInfo->MakeTextStatus(false); + NZBInfo* nzbInfo = historyInfo->GetNZBInfo(); + status = nzbInfo->MakeTextStatus(false); } - else if (pHistoryInfo->GetKind() == HistoryInfo::hkDup) + else if (historyInfo->GetKind() == HistoryInfo::hkDup) { - DupInfo* pDupInfo = pHistoryInfo->GetDupInfo(); - const char* szDupStatusName[] = { "FAILURE/INTERNAL_ERROR", "SUCCESS/HIDDEN", "FAILURE/HIDDEN", + DupInfo* dupInfo = historyInfo->GetDupInfo(); + const char* dupStatusName[] = { "FAILURE/INTERNAL_ERROR", "SUCCESS/HIDDEN", "FAILURE/HIDDEN", "DELETED/MANUAL", "DELETED/DUPE", "FAILURE/BAD", "SUCCESS/GOOD" }; - szStatus = szDupStatusName[pDupInfo->GetStatus()]; + status = dupStatusName[dupInfo->GetStatus()]; } - return szStatus; + return status; } // Deprecated in v13 @@ -2727,24 +2727,24 @@ void UrlQueueXmlCommand::Execute() "\"Priority\" : %i\n" "}"; - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); + DownloadQueue* downloadQueue = DownloadQueue::Lock(); int index = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; + NZBInfo* nzbInfo = *it; - if (pNZBInfo->GetKind() == NZBInfo::nkUrl) + if (nzbInfo->GetKind() == NZBInfo::nkUrl) { - char* xmlNicename = EncodeStr(pNZBInfo->GetName()); - char* xmlNZBFilename = EncodeStr(pNZBInfo->GetFilename()); - char* xmlURL = EncodeStr(pNZBInfo->GetURL()); - char* xmlCategory = EncodeStr(pNZBInfo->GetCategory()); + char* xmlNicename = EncodeStr(nzbInfo->GetName()); + char* xmlNZBFilename = EncodeStr(nzbInfo->GetFilename()); + char* xmlURL = EncodeStr(nzbInfo->GetURL()); + char* xmlCategory = EncodeStr(nzbInfo->GetCategory()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_URLQUEUE_ITEM : XML_URLQUEUE_ITEM, - pNZBInfo->GetID(), xmlNZBFilename, xmlURL, xmlNicename, xmlCategory, pNZBInfo->GetPriority()); + nzbInfo->GetID(), xmlNZBFilename, xmlURL, xmlNicename, xmlCategory, nzbInfo->GetPriority()); free(xmlNicename); free(xmlNZBFilename); @@ -2777,15 +2777,15 @@ void ConfigXmlCommand::Execute() int index = 0; - Options::OptEntries* pOptEntries = g_pOptions->LockOptEntries(); + Options::OptEntries* optEntries = g_pOptions->LockOptEntries(); - for (Options::OptEntries::iterator it = pOptEntries->begin(); it != pOptEntries->end(); it++) + for (Options::OptEntries::iterator it = optEntries->begin(); it != optEntries->end(); it++) { - Options::OptEntry* pOptEntry = *it; + Options::OptEntry* optEntry = *it; - char* xmlName = EncodeStr(pOptEntry->GetName()); - char* xmlValue = EncodeStr(m_eUserAccess == XmlRpcProcessor::uaRestricted && - pOptEntry->Restricted() ? "***" : pOptEntry->GetValue()); + char* xmlName = EncodeStr(optEntry->GetName()); + char* xmlValue = EncodeStr(m_userAccess == XmlRpcProcessor::uaRestricted && + optEntry->Restricted() ? "***" : optEntry->GetValue()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_CONFIG_ITEM : XML_CONFIG_ITEM, xmlName, xmlValue); @@ -2814,11 +2814,11 @@ void LoadConfigXmlCommand::Execute() "\"Value\" : \"%s\"\n" "}"; - Options::OptEntries* pOptEntries = new Options::OptEntries(); - if (!g_pScriptConfig->LoadConfig(pOptEntries)) + Options::OptEntries* optEntries = new Options::OptEntries(); + if (!g_pScriptConfig->LoadConfig(optEntries)) { BuildErrorResponse(3, "Could not read configuration file"); - delete pOptEntries; + delete optEntries; return; } @@ -2826,13 +2826,13 @@ void LoadConfigXmlCommand::Execute() int index = 0; - for (Options::OptEntries::iterator it = pOptEntries->begin(); it != pOptEntries->end(); it++) + for (Options::OptEntries::iterator it = optEntries->begin(); it != optEntries->end(); it++) { - Options::OptEntry* pOptEntry = *it; + Options::OptEntry* optEntry = *it; - char* xmlName = EncodeStr(pOptEntry->GetName()); - char* xmlValue = EncodeStr(m_eUserAccess == XmlRpcProcessor::uaRestricted && - pOptEntry->Restricted() ? "***" : pOptEntry->GetValue()); + char* xmlName = EncodeStr(optEntry->GetName()); + char* xmlValue = EncodeStr(m_userAccess == XmlRpcProcessor::uaRestricted && + optEntry->Restricted() ? "***" : optEntry->GetValue()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_CONFIG_ITEM : XML_CONFIG_ITEM, xmlName, xmlValue); @@ -2841,7 +2841,7 @@ void LoadConfigXmlCommand::Execute() free(xmlValue); } - delete pOptEntries; + delete optEntries; AppendResponse(IsJson() ? "\n]" : "\n"); } @@ -2849,26 +2849,26 @@ void LoadConfigXmlCommand::Execute() // bool saveconfig(struct[] data) void SaveConfigXmlCommand::Execute() { - Options::OptEntries* pOptEntries = new Options::OptEntries(); + Options::OptEntries* optEntries = new Options::OptEntries(); - char* szName; - char* szValue; - char* szDummy; - while ((IsJson() && NextParamAsStr(&szDummy) && NextParamAsStr(&szName) && - NextParamAsStr(&szDummy) && NextParamAsStr(&szValue)) || - (!IsJson() && NextParamAsStr(&szName) && NextParamAsStr(&szValue))) + char* name; + char* value; + char* dummy; + while ((IsJson() && NextParamAsStr(&dummy) && NextParamAsStr(&name) && + NextParamAsStr(&dummy) && NextParamAsStr(&value)) || + (!IsJson() && NextParamAsStr(&name) && NextParamAsStr(&value))) { - DecodeStr(szName); - DecodeStr(szValue); - pOptEntries->push_back(new Options::OptEntry(szName, szValue)); + DecodeStr(name); + DecodeStr(value); + optEntries->push_back(new Options::OptEntry(name, value)); } // save to config file - bool bOK = g_pScriptConfig->SaveConfig(pOptEntries); + bool ok = g_pScriptConfig->SaveConfig(optEntries); - delete pOptEntries; + delete optEntries; - BuildBoolResponse(bOK); + BuildBoolResponse(ok); } // struct[] configtemplates(bool loadFromDisk) @@ -2899,18 +2899,18 @@ void ConfigTemplatesXmlCommand::Execute() "\"Template\" : \"%s\"\n" "}"; - bool bLoadFromDisk = false; - NextParamAsBool(&bLoadFromDisk); + bool loadFromDisk = false; + NextParamAsBool(&loadFromDisk); - ScriptConfig::ConfigTemplates* pConfigTemplates = g_pScriptConfig->GetConfigTemplates(); + ScriptConfig::ConfigTemplates* configTemplates = g_pScriptConfig->GetConfigTemplates(); - if (bLoadFromDisk) + if (loadFromDisk) { - pConfigTemplates = new ScriptConfig::ConfigTemplates(); - if (!g_pScriptConfig->LoadConfigTemplates(pConfigTemplates)) + configTemplates = new ScriptConfig::ConfigTemplates(); + if (!g_pScriptConfig->LoadConfigTemplates(configTemplates)) { BuildErrorResponse(3, "Could not read configuration templates"); - delete pConfigTemplates; + delete configTemplates; return; } } @@ -2919,22 +2919,22 @@ void ConfigTemplatesXmlCommand::Execute() int index = 0; - for (ScriptConfig::ConfigTemplates::iterator it = pConfigTemplates->begin(); it != pConfigTemplates->end(); it++) + for (ScriptConfig::ConfigTemplates::iterator it = configTemplates->begin(); it != configTemplates->end(); it++) { - ScriptConfig::ConfigTemplate* pConfigTemplate = *it; + ScriptConfig::ConfigTemplate* configTemplate = *it; - char* xmlName = EncodeStr(pConfigTemplate->GetScript() ? pConfigTemplate->GetScript()->GetName() : ""); - char* xmlDisplayName = EncodeStr(pConfigTemplate->GetScript() ? pConfigTemplate->GetScript()->GetDisplayName() : ""); - char* xmlTemplate = EncodeStr(pConfigTemplate->GetTemplate()); + char* xmlName = EncodeStr(configTemplate->GetScript() ? configTemplate->GetScript()->GetName() : ""); + char* xmlDisplayName = EncodeStr(configTemplate->GetScript() ? configTemplate->GetScript()->GetDisplayName() : ""); + char* xmlTemplate = EncodeStr(configTemplate->GetTemplate()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_CONFIG_ITEM : XML_CONFIG_ITEM, xmlName, xmlDisplayName, - BoolToStr(pConfigTemplate->GetScript() && pConfigTemplate->GetScript()->GetPostScript()), - BoolToStr(pConfigTemplate->GetScript() && pConfigTemplate->GetScript()->GetScanScript()), - BoolToStr(pConfigTemplate->GetScript() && pConfigTemplate->GetScript()->GetQueueScript()), - BoolToStr(pConfigTemplate->GetScript() && pConfigTemplate->GetScript()->GetSchedulerScript()), - BoolToStr(pConfigTemplate->GetScript() && pConfigTemplate->GetScript()->GetFeedScript()), + BoolToStr(configTemplate->GetScript() && configTemplate->GetScript()->GetPostScript()), + BoolToStr(configTemplate->GetScript() && configTemplate->GetScript()->GetScanScript()), + BoolToStr(configTemplate->GetScript() && configTemplate->GetScript()->GetQueueScript()), + BoolToStr(configTemplate->GetScript() && configTemplate->GetScript()->GetSchedulerScript()), + BoolToStr(configTemplate->GetScript() && configTemplate->GetScript()->GetFeedScript()), xmlTemplate); free(xmlName); @@ -2942,17 +2942,17 @@ void ConfigTemplatesXmlCommand::Execute() free(xmlTemplate); } - if (bLoadFromDisk) + if (loadFromDisk) { - delete pConfigTemplates; + delete configTemplates; } AppendResponse(IsJson() ? "\n]" : "\n"); } -ViewFeedXmlCommand::ViewFeedXmlCommand(bool bPreview) +ViewFeedXmlCommand::ViewFeedXmlCommand(bool preview) { - m_bPreview = bPreview; + m_preview = preview; } // struct[] viewfeed(int id) @@ -2964,66 +2964,66 @@ ViewFeedXmlCommand::ViewFeedXmlCommand(bool bPreview) // int priority, int interval, string feedfilter, bool includeNonMatching, int cacheTimeSec, string cacheId) void ViewFeedXmlCommand::Execute() { - bool bOK = false; - bool bIncludeNonMatching = false; - FeedItemInfos* pFeedItemInfos = NULL; + bool ok = false; + bool includeNonMatching = false; + FeedItemInfos* feedItemInfos = NULL; - if (m_bPreview) + if (m_preview) { - int iID = 0; - char* szName; - char* szUrl; - char* szFilter; - bool bBacklog = true; - bool bPauseNzb; - char* szCategory; - int iInterval = 0; - int iPriority; - char* szFeedFilter = NULL; - char* szCacheId; - int iCacheTimeSec; + int id = 0; + char* name; + char* url; + char* filter; + bool backlog = true; + bool pauseNzb; + char* category; + int interval = 0; + int priority; + char* feedFilter = NULL; + char* cacheId; + int cacheTimeSec; // if the first parameter is int then it's the v16 signature - bool bV16 = NextParamAsInt(&iID); + bool v16 = NextParamAsInt(&id); - if (!NextParamAsStr(&szName) || !NextParamAsStr(&szUrl) || !NextParamAsStr(&szFilter) || - (bV16 && !NextParamAsBool(&bBacklog)) || !NextParamAsBool(&bPauseNzb) || - !NextParamAsStr(&szCategory) || !NextParamAsInt(&iPriority) || - (bV16 && (!NextParamAsInt(&iInterval) || !NextParamAsStr(&szFeedFilter))) || - !NextParamAsBool(&bIncludeNonMatching) || !NextParamAsInt(&iCacheTimeSec) || - !NextParamAsStr(&szCacheId)) + if (!NextParamAsStr(&name) || !NextParamAsStr(&url) || !NextParamAsStr(&filter) || + (v16 && !NextParamAsBool(&backlog)) || !NextParamAsBool(&pauseNzb) || + !NextParamAsStr(&category) || !NextParamAsInt(&priority) || + (v16 && (!NextParamAsInt(&interval) || !NextParamAsStr(&feedFilter))) || + !NextParamAsBool(&includeNonMatching) || !NextParamAsInt(&cacheTimeSec) || + !NextParamAsStr(&cacheId)) { BuildErrorResponse(2, "Invalid parameter"); return; } - DecodeStr(szName); - DecodeStr(szUrl); - DecodeStr(szFilter); - DecodeStr(szCacheId); - DecodeStr(szCategory); + DecodeStr(name); + DecodeStr(url); + DecodeStr(filter); + DecodeStr(cacheId); + DecodeStr(category); - debug("Url=%s", szUrl); - debug("Filter=%s", szFilter); + debug("Url=%s", url); + debug("Filter=%s", filter); - bOK = g_pFeedCoordinator->PreviewFeed(iID, szName, szUrl, szFilter, bBacklog, bPauseNzb, - szCategory, iPriority, iInterval, szFeedFilter, iCacheTimeSec, szCacheId, &pFeedItemInfos); + ok = g_pFeedCoordinator->PreviewFeed(id, name, url, filter, backlog, pauseNzb, + category, priority, interval, feedFilter, cacheTimeSec, cacheId, &feedItemInfos); } else { - int iID = 0; - if (!NextParamAsInt(&iID) || !NextParamAsBool(&bIncludeNonMatching)) + int id = 0; + if (!NextParamAsInt(&id) || !NextParamAsBool(&includeNonMatching)) { BuildErrorResponse(2, "Invalid parameter"); return; } - debug("ID=%i", iID); + debug("ID=%i", id); - bOK = g_pFeedCoordinator->ViewFeed(iID, &pFeedItemInfos); + ok = g_pFeedCoordinator->ViewFeed(id, &feedItemInfos); } - if (!bOK) + if (!ok) { BuildErrorResponse(3, "Could not read feed"); return; @@ -3071,37 +3071,37 @@ void ViewFeedXmlCommand::Execute() "\"Status\" : \"%s\"\n" "}"; - const char* szStatusType[] = { "UNKNOWN", "BACKLOG", "FETCHED", "NEW" }; - const char* szMatchStatusType[] = { "IGNORED", "ACCEPTED", "REJECTED" }; - const char* szDupeModeType[] = { "SCORE", "ALL", "FORCE" }; + const char* statusType[] = { "UNKNOWN", "BACKLOG", "FETCHED", "NEW" }; + const char* matchStatusType[] = { "IGNORED", "ACCEPTED", "REJECTED" }; + const char* dupeModeType[] = { "SCORE", "ALL", "FORCE" }; AppendResponse(IsJson() ? "[\n" : "\n"); int index = 0; - for (FeedItemInfos::iterator it = pFeedItemInfos->begin(); it != pFeedItemInfos->end(); it++) + for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) { - FeedItemInfo* pFeedItemInfo = *it; + FeedItemInfo* feedItemInfo = *it; - if (bIncludeNonMatching || pFeedItemInfo->GetMatchStatus() == FeedItemInfo::msAccepted) + if (includeNonMatching || feedItemInfo->GetMatchStatus() == FeedItemInfo::msAccepted) { - unsigned long iSizeHi, iSizeLo; - Util::SplitInt64(pFeedItemInfo->GetSize(), &iSizeHi, &iSizeLo); - int iSizeMB = (int)(pFeedItemInfo->GetSize() / 1024 / 1024); + unsigned long sizeHi, sizeLo; + Util::SplitInt64(feedItemInfo->GetSize(), &sizeHi, &sizeLo); + int sizeMB = (int)(feedItemInfo->GetSize() / 1024 / 1024); - char* xmltitle = EncodeStr(pFeedItemInfo->GetTitle()); - char* xmlfilename = EncodeStr(pFeedItemInfo->GetFilename()); - char* xmlurl = EncodeStr(pFeedItemInfo->GetUrl()); - char* xmlcategory = EncodeStr(pFeedItemInfo->GetCategory()); - char* xmladdcategory = EncodeStr(pFeedItemInfo->GetAddCategory()); - char* xmldupekey = EncodeStr(pFeedItemInfo->GetDupeKey()); + char* xmltitle = EncodeStr(feedItemInfo->GetTitle()); + char* xmlfilename = EncodeStr(feedItemInfo->GetFilename()); + char* xmlurl = EncodeStr(feedItemInfo->GetUrl()); + char* xmlcategory = EncodeStr(feedItemInfo->GetCategory()); + char* xmladdcategory = EncodeStr(feedItemInfo->GetAddCategory()); + char* xmldupekey = EncodeStr(feedItemInfo->GetDupeKey()); AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_FEED_ITEM : XML_FEED_ITEM, - xmltitle, xmlfilename, xmlurl, iSizeLo, iSizeHi, iSizeMB, xmlcategory, xmladdcategory, - BoolToStr(pFeedItemInfo->GetPauseNzb()), pFeedItemInfo->GetPriority(), pFeedItemInfo->GetTime(), - szMatchStatusType[pFeedItemInfo->GetMatchStatus()], pFeedItemInfo->GetMatchRule(), - xmldupekey, pFeedItemInfo->GetDupeScore(), szDupeModeType[pFeedItemInfo->GetDupeMode()], - szStatusType[pFeedItemInfo->GetStatus()]); + xmltitle, xmlfilename, xmlurl, sizeLo, sizeHi, sizeMB, xmlcategory, xmladdcategory, + BoolToStr(feedItemInfo->GetPauseNzb()), feedItemInfo->GetPriority(), feedItemInfo->GetTime(), + matchStatusType[feedItemInfo->GetMatchStatus()], feedItemInfo->GetMatchRule(), + xmldupekey, feedItemInfo->GetDupeScore(), dupeModeType[feedItemInfo->GetDupeMode()], + statusType[feedItemInfo->GetStatus()]); free(xmltitle); free(xmlfilename); @@ -3112,7 +3112,7 @@ void ViewFeedXmlCommand::Execute() } } - pFeedItemInfos->Release(); + feedItemInfos->Release(); AppendResponse(IsJson() ? "\n]" : "\n"); } @@ -3125,14 +3125,14 @@ void FetchFeedXmlCommand::Execute() return; } - int iID; - if (!NextParamAsInt(&iID)) + int id; + if (!NextParamAsInt(&id)) { BuildErrorResponse(2, "Invalid parameter (ID)"); return; } - g_pFeedCoordinator->FetchFeed(iID); + g_pFeedCoordinator->FetchFeed(id); BuildBoolResponse(true); } @@ -3145,16 +3145,16 @@ void EditServerXmlCommand::Execute() return; } - bool bOK = false; - int bFirst = true; + bool ok = false; + int first = true; - int iID; - while (NextParamAsInt(&iID)) + int id; + while (NextParamAsInt(&id)) { - bFirst = false; + first = false; - bool bActive; - if (!NextParamAsBool(&bActive)) + bool active; + if (!NextParamAsBool(&active)) { BuildErrorResponse(2, "Invalid parameter"); return; @@ -3162,78 +3162,78 @@ void EditServerXmlCommand::Execute() for (Servers::iterator it = g_pServerPool->GetServers()->begin(); it != g_pServerPool->GetServers()->end(); it++) { - NewsServer* pServer = *it; - if (pServer->GetID() == iID) + NewsServer* server = *it; + if (server->GetID() == id) { - pServer->SetActive(bActive); - bOK = true; + server->SetActive(active); + ok = true; } } } - if (bFirst) + if (first) { BuildErrorResponse(2, "Invalid parameter"); return; } - if (bOK) + if (ok) { g_pServerPool->Changed(); } - BuildBoolResponse(bOK); + BuildBoolResponse(ok); } // string readurl(string url, string infoname) void ReadUrlXmlCommand::Execute() { - char* szURL; - if (!NextParamAsStr(&szURL)) + char* url; + if (!NextParamAsStr(&url)) { BuildErrorResponse(2, "Invalid parameter (URL)"); return; } - DecodeStr(szURL); + DecodeStr(url); - char* szInfoName; - if (!NextParamAsStr(&szInfoName)) + char* infoName; + if (!NextParamAsStr(&infoName)) { BuildErrorResponse(2, "Invalid parameter (InfoName)"); return; } - DecodeStr(szInfoName); + DecodeStr(infoName); // generate temp file name - char szTempFileName[1024]; - int iNum = 1; - while (iNum == 1 || Util::FileExists(szTempFileName)) + char tempFileName[1024]; + int num = 1; + while (num == 1 || Util::FileExists(tempFileName)) { - snprintf(szTempFileName, 1024, "%sreadurl-%i.tmp", g_pOptions->GetTempDir(), iNum); - szTempFileName[1024-1] = '\0'; - iNum++; + snprintf(tempFileName, 1024, "%sreadurl-%i.tmp", g_pOptions->GetTempDir(), num); + tempFileName[1024-1] = '\0'; + num++; } - WebDownloader* pDownloader = new WebDownloader(); - pDownloader->SetURL(szURL); - pDownloader->SetForce(true); - pDownloader->SetRetry(false); - pDownloader->SetOutputFilename(szTempFileName); - pDownloader->SetInfoName(szInfoName); + WebDownloader* downloader = new WebDownloader(); + downloader->SetURL(url); + downloader->SetForce(true); + downloader->SetRetry(false); + downloader->SetOutputFilename(tempFileName); + downloader->SetInfoName(infoName); // do sync download - WebDownloader::EStatus eStatus = pDownloader->DownloadWithRedirects(5); - bool bOK = eStatus == WebDownloader::adFinished; + WebDownloader::EStatus status = downloader->DownloadWithRedirects(5); + bool ok = status == WebDownloader::adFinished; - delete pDownloader; + delete downloader; - if (bOK) + if (ok) { - char* szFileContent = NULL; - int iFileContentLen = 0; - Util::LoadFileIntoBuffer(szTempFileName, &szFileContent, &iFileContentLen); - char* xmlContent = EncodeStr(szFileContent); - free(szFileContent); + char* fileContent = NULL; + int fileContentLen = 0; + Util::LoadFileIntoBuffer(tempFileName, &fileContent, &fileContentLen); + char* xmlContent = EncodeStr(fileContent); + free(fileContent); AppendResponse(IsJson() ? "\"" : ""); AppendResponse(xmlContent); AppendResponse(IsJson() ? "\"" : ""); @@ -3244,19 +3244,19 @@ void ReadUrlXmlCommand::Execute() BuildErrorResponse(3, "Could not read url"); } - remove(szTempFileName); + remove(tempFileName); } // string checkupdates() void CheckUpdatesXmlCommand::Execute() { - char* szUpdateInfo = NULL; - bool bOK = g_pMaintenance->CheckUpdates(&szUpdateInfo); + char* updateInfo = NULL; + bool ok = g_pMaintenance->CheckUpdates(&updateInfo); - if (bOK) + if (ok) { - char* xmlContent = EncodeStr(szUpdateInfo); - free(szUpdateInfo); + char* xmlContent = EncodeStr(updateInfo); + free(updateInfo); AppendResponse(IsJson() ? "\"" : ""); AppendResponse(xmlContent); AppendResponse(IsJson() ? "\"" : ""); @@ -3276,26 +3276,26 @@ void StartUpdateXmlCommand::Execute() return; } - char* szBranch; - if (!NextParamAsStr(&szBranch)) + char* branchName; + if (!NextParamAsStr(&branchName)) { BuildErrorResponse(2, "Invalid parameter (Branch)"); return; } - DecodeStr(szBranch); + DecodeStr(branchName); - Maintenance::EBranch eBranch; - if (!strcasecmp(szBranch, "stable")) + Maintenance::EBranch branch; + if (!strcasecmp(branchName, "stable")) { - eBranch = Maintenance::brStable; + branch = Maintenance::brStable; } - else if (!strcasecmp(szBranch, "testing")) + else if (!strcasecmp(branchName, "testing")) { - eBranch = Maintenance::brTesting; + branch = Maintenance::brTesting; } - else if (!strcasecmp(szBranch, "devel")) + else if (!strcasecmp(branchName, "devel")) { - eBranch = Maintenance::brDevel; + branch = Maintenance::brDevel; } else { @@ -3303,9 +3303,9 @@ void StartUpdateXmlCommand::Execute() return; } - bool bOK = g_pMaintenance->StartUpdate(eBranch); + bool ok = g_pMaintenance->StartUpdate(branch); - BuildBoolResponse(bOK); + BuildBoolResponse(ok); } // struct[] logupdate(idfrom, entries) @@ -3390,51 +3390,51 @@ void ServerVolumesXmlCommand::Execute() AppendResponse(IsJson() ? "[\n" : "\n"); - ServerVolumes* pServerVolumes = g_pStatMeter->LockServerVolumes(); + ServerVolumes* serverVolumes = g_pStatMeter->LockServerVolumes(); int index = 0; - for (ServerVolumes::iterator it = pServerVolumes->begin(); it != pServerVolumes->end(); it++, index++) + for (ServerVolumes::iterator it = serverVolumes->begin(); it != serverVolumes->end(); it++, index++) { - ServerVolume* pServerVolume = *it; + ServerVolume* serverVolume = *it; - unsigned long iTotalSizeHi, iTotalSizeLo, iTotalSizeMB; - Util::SplitInt64(pServerVolume->GetTotalBytes(), &iTotalSizeHi, &iTotalSizeLo); - iTotalSizeMB = (int)(pServerVolume->GetTotalBytes() / 1024 / 1024); + unsigned long totalSizeHi, totalSizeLo, totalSizeMB; + Util::SplitInt64(serverVolume->GetTotalBytes(), &totalSizeHi, &totalSizeLo); + totalSizeMB = (int)(serverVolume->GetTotalBytes() / 1024 / 1024); - unsigned long iCustomSizeHi, iCustomSizeLo, iCustomSizeMB; - Util::SplitInt64(pServerVolume->GetCustomBytes(), &iCustomSizeHi, &iCustomSizeLo); - iCustomSizeMB = (int)(pServerVolume->GetCustomBytes() / 1024 / 1024); + unsigned long customSizeHi, customSizeLo, customSizeMB; + Util::SplitInt64(serverVolume->GetCustomBytes(), &customSizeHi, &customSizeLo); + customSizeMB = (int)(serverVolume->GetCustomBytes() / 1024 / 1024); AppendCondResponse(",\n", IsJson() && index > 0); AppendFmtResponse(IsJson() ? JSON_VOLUME_ITEM_START : XML_VOLUME_ITEM_START, - index, (int)pServerVolume->GetDataTime(), pServerVolume->GetFirstDay(), - iTotalSizeLo, iTotalSizeHi, iTotalSizeMB, iCustomSizeLo, iCustomSizeHi, iCustomSizeMB, - (int)pServerVolume->GetCustomTime(), pServerVolume->GetSecSlot(), - pServerVolume->GetMinSlot(), pServerVolume->GetHourSlot(), pServerVolume->GetDaySlot()); + index, (int)serverVolume->GetDataTime(), serverVolume->GetFirstDay(), + totalSizeLo, totalSizeHi, totalSizeMB, customSizeLo, customSizeHi, customSizeMB, + (int)serverVolume->GetCustomTime(), serverVolume->GetSecSlot(), + serverVolume->GetMinSlot(), serverVolume->GetHourSlot(), serverVolume->GetDaySlot()); - ServerVolume::VolumeArray* VolumeArrays[] = { pServerVolume->BytesPerSeconds(), - pServerVolume->BytesPerMinutes(), pServerVolume->BytesPerHours(), pServerVolume->BytesPerDays() }; + ServerVolume::VolumeArray* VolumeArrays[] = { serverVolume->BytesPerSeconds(), + serverVolume->BytesPerMinutes(), serverVolume->BytesPerHours(), serverVolume->BytesPerDays() }; const char* VolumeNames[] = { "BytesPerSeconds", "BytesPerMinutes", "BytesPerHours", "BytesPerDays" }; for (int i=0; i<4; i++) { - ServerVolume::VolumeArray* pVolumeArray = VolumeArrays[i]; - const char* szArrayName = VolumeNames[i]; + ServerVolume::VolumeArray* volumeArray = VolumeArrays[i]; + const char* arrayName = VolumeNames[i]; - AppendFmtResponse(IsJson() ? JSON_BYTES_ARRAY_START : XML_BYTES_ARRAY_START, szArrayName); + AppendFmtResponse(IsJson() ? JSON_BYTES_ARRAY_START : XML_BYTES_ARRAY_START, arrayName); int index2 = 0; - for (ServerVolume::VolumeArray::iterator it2 = pVolumeArray->begin(); it2 != pVolumeArray->end(); it2++) + for (ServerVolume::VolumeArray::iterator it2 = volumeArray->begin(); it2 != volumeArray->end(); it2++) { - long long lBytes = *it2; - unsigned long iSizeHi, iSizeLo, iSizeMB; - Util::SplitInt64(lBytes, &iSizeHi, &iSizeLo); - iSizeMB = (int)(lBytes / 1024 / 1024); + long long bytes = *it2; + unsigned long sizeHi, sizeLo, sizeMB; + Util::SplitInt64(bytes, &sizeHi, &sizeLo); + sizeMB = (int)(bytes / 1024 / 1024); AppendCondResponse(",\n", IsJson() && index2++ > 0); AppendFmtResponse(IsJson() ? JSON_BYTES_ARRAY_ITEM : XML_BYTES_ARRAY_ITEM, - iSizeLo, iSizeHi, iSizeMB); + sizeLo, sizeHi, sizeMB); } AppendResponse(IsJson() ? JSON_BYTES_ARRAY_END : XML_BYTES_ARRAY_END); @@ -3456,43 +3456,43 @@ void ResetServerVolumeXmlCommand::Execute() return; } - int iServerId; - char* szCounter; - if (!NextParamAsInt(&iServerId) || !NextParamAsStr(&szCounter)) + int serverId; + char* counter; + if (!NextParamAsInt(&serverId) || !NextParamAsStr(&counter)) { BuildErrorResponse(2, "Invalid parameter"); return; } - if (strcmp(szCounter, "CUSTOM")) + if (strcmp(counter, "CUSTOM")) { BuildErrorResponse(3, "Invalid Counter"); return; } - bool bOK = false; - ServerVolumes* pServerVolumes = g_pStatMeter->LockServerVolumes(); + bool ok = false; + ServerVolumes* serverVolumes = g_pStatMeter->LockServerVolumes(); int index = 0; - for (ServerVolumes::iterator it = pServerVolumes->begin(); it != pServerVolumes->end(); it++, index++) + for (ServerVolumes::iterator it = serverVolumes->begin(); it != serverVolumes->end(); it++, index++) { - ServerVolume* pServerVolume = *it; - if (index == iServerId || iServerId == -1) + ServerVolume* serverVolume = *it; + if (index == serverId || serverId == -1) { - pServerVolume->ResetCustom(); - bOK = true; + serverVolume->ResetCustom(); + ok = true; } } g_pStatMeter->UnlockServerVolumes(); - BuildBoolResponse(bOK); + BuildBoolResponse(ok); } // struct[] loadlog(nzbid, logidfrom, logentries) void LoadLogXmlCommand::Execute() { - m_pNZBInfo = NULL; - m_iNZBID = 0; - if (!NextParamAsInt(&m_iNZBID)) + m_nzbInfo = NULL; + m_nzbId = 0; + if (!NextParamAsInt(&m_nzbId)) { BuildErrorResponse(2, "Invalid parameter"); return; @@ -3504,15 +3504,15 @@ void LoadLogXmlCommand::Execute() MessageList* LoadLogXmlCommand::LockMessages() { // TODO: optimize for m_iIDFrom and m_iNrEntries - g_pDiskState->LoadNZBMessages(m_iNZBID, &m_messages); + g_pDiskState->LoadNZBMessages(m_nzbId, &m_messages); if (m_messages.empty()) { - DownloadQueue* pDownloadQueue = DownloadQueue::Lock(); - m_pNZBInfo = pDownloadQueue->GetQueue()->Find(m_iNZBID); - if (m_pNZBInfo) + DownloadQueue* downloadQueue = DownloadQueue::Lock(); + m_nzbInfo = downloadQueue->GetQueue()->Find(m_nzbId); + if (m_nzbInfo) { - return m_pNZBInfo->LockCachedMessages(); + return m_nzbInfo->LockCachedMessages(); } else { @@ -3525,9 +3525,9 @@ MessageList* LoadLogXmlCommand::LockMessages() void LoadLogXmlCommand::UnlockMessages() { - if (m_pNZBInfo) + if (m_nzbInfo) { - m_pNZBInfo->UnlockCachedMessages(); + m_nzbInfo->UnlockCachedMessages(); DownloadQueue::Unlock(); } } @@ -3543,44 +3543,44 @@ void TestServerXmlCommand::Execute() return; } - char* szHost; - int iPort; - char* szUsername; - char* szPassword; - bool bEncryption; - char* szCipher; - int iTimeout; + char* host; + int port; + char* username; + char* password; + bool encryption; + char* cipher; + int timeout; - if (!NextParamAsStr(&szHost) || !NextParamAsInt(&iPort) || !NextParamAsStr(&szUsername) || - !NextParamAsStr(&szPassword) || !NextParamAsBool(&bEncryption) || - !NextParamAsStr(&szCipher) || !NextParamAsInt(&iTimeout)) + if (!NextParamAsStr(&host) || !NextParamAsInt(&port) || !NextParamAsStr(&username) || + !NextParamAsStr(&password) || !NextParamAsBool(&encryption) || + !NextParamAsStr(&cipher) || !NextParamAsInt(&timeout)) { BuildErrorResponse(2, "Invalid parameter"); return; } - NewsServer server(0, true, "test server", szHost, iPort, szUsername, szPassword, false, bEncryption, szCipher, 1, 0, 0, 0); - TestConnection* pConnection = new TestConnection(&server, this); - pConnection->SetTimeout(iTimeout == 0 ? g_pOptions->GetArticleTimeout() : iTimeout); - pConnection->SetSuppressErrors(false); - m_szErrText = NULL; + NewsServer server(0, true, "test server", host, port, username, password, false, encryption, cipher, 1, 0, 0, 0); + TestConnection* connection = new TestConnection(&server, this); + connection->SetTimeout(timeout == 0 ? g_pOptions->GetArticleTimeout() : timeout); + connection->SetSuppressErrors(false); + m_errText = NULL; - bool bOK = pConnection->Connect(); + bool ok = connection->Connect(); - char szContent[1024]; - snprintf(szContent, 1024, IsJson() ? JSON_RESPONSE_STR_BODY : XML_RESPONSE_STR_BODY, - bOK ? "" : Util::EmptyStr(m_szErrText) ? "Unknown error" : m_szErrText); - szContent[1024-1] = '\0'; + char content[1024]; + snprintf(content, 1024, IsJson() ? JSON_RESPONSE_STR_BODY : XML_RESPONSE_STR_BODY, + ok ? "" : Util::EmptyStr(m_errText) ? "Unknown error" : m_errText); + content[1024-1] = '\0'; - AppendResponse(szContent); + AppendResponse(content); - delete pConnection; + delete connection; } -void TestServerXmlCommand::PrintError(const char* szErrMsg) +void TestServerXmlCommand::PrintError(const char* errMsg) { - if (!m_szErrText) + if (!m_errText) { - m_szErrText = EncodeStr(szErrMsg); + m_errText = EncodeStr(errMsg); } } diff --git a/daemon/remote/XmlRpc.h b/daemon/remote/XmlRpc.h index 1da81221..e690a335 100644 --- a/daemon/remote/XmlRpc.h +++ b/daemon/remote/XmlRpc.h @@ -56,73 +56,73 @@ public: }; private: - char* m_szRequest; - const char* m_szContentType; - ERpcProtocol m_eProtocol; - EHttpMethod m_eHttpMethod; - EUserAccess m_eUserAccess; - char* m_szUrl; + char* m_request; + const char* m_contentType; + ERpcProtocol m_protocol; + EHttpMethod m_httpMethod; + EUserAccess m_userAccess; + char* m_url; StringBuilder m_cResponse; void Dispatch(); - XmlCommand* CreateCommand(const char* szMethodName); + XmlCommand* CreateCommand(const char* methodName); void MutliCall(); - void BuildResponse(const char* szResponse, const char* szCallbackFunc, bool bFault, const char* szRequestId); + void BuildResponse(const char* response, const char* callbackFunc, bool fault, const char* requestId); public: XmlRpcProcessor(); ~XmlRpcProcessor(); void Execute(); - void SetHttpMethod(EHttpMethod eHttpMethod) { m_eHttpMethod = eHttpMethod; } - void SetUserAccess(EUserAccess eUserAccess) { m_eUserAccess = eUserAccess; } - void SetUrl(const char* szUrl); - void SetRequest(char* szRequest) { m_szRequest = szRequest; } + void SetHttpMethod(EHttpMethod httpMethod) { m_httpMethod = httpMethod; } + void SetUserAccess(EUserAccess userAccess) { m_userAccess = userAccess; } + void SetUrl(const char* url); + void SetRequest(char* request) { m_request = request; } const char* GetResponse() { return m_cResponse.GetBuffer(); } - const char* GetContentType() { return m_szContentType; } - static bool IsRpcRequest(const char* szUrl); + const char* GetContentType() { return m_contentType; } + static bool IsRpcRequest(const char* url); }; class XmlCommand { protected: - char* m_szRequest; - char* m_szRequestPtr; - char* m_szCallbackFunc; - StringBuilder m_StringBuilder; - bool m_bFault; - XmlRpcProcessor::ERpcProtocol m_eProtocol; - XmlRpcProcessor::EHttpMethod m_eHttpMethod; - XmlRpcProcessor::EUserAccess m_eUserAccess; + char* m_request; + char* m_requestPtr; + char* m_callbackFunc; + StringBuilder m_stringBuilder; + bool m_fault; + XmlRpcProcessor::ERpcProtocol m_protocol; + XmlRpcProcessor::EHttpMethod m_httpMethod; + XmlRpcProcessor::EUserAccess m_userAccess; - void BuildErrorResponse(int iErrCode, const char* szErrText, ...); - void BuildBoolResponse(bool bOK); - void BuildIntResponse(int iValue); - void AppendResponse(const char* szPart); - void AppendFmtResponse(const char* szFormat, ...); - void AppendCondResponse(const char* szPart, bool bCond); - void OptimizeResponse(int iRecordCount); + void BuildErrorResponse(int errCode, const char* errText, ...); + void BuildBoolResponse(bool ok); + void BuildIntResponse(int value); + void AppendResponse(const char* part); + void AppendFmtResponse(const char* format, ...); + void AppendCondResponse(const char* part, bool cond); + void OptimizeResponse(int recordCount); bool IsJson(); bool CheckSafeMethod(); - bool NextParamAsInt(int* iValue); - bool NextParamAsBool(bool* bValue); - bool NextParamAsStr(char** szValueBuf); - char* XmlNextValue(char* szXml, const char* szTag, int* pValueLength); - const char* BoolToStr(bool bValue); - char* EncodeStr(const char* szStr); - void DecodeStr(char* szStr); + bool NextParamAsInt(int* value); + bool NextParamAsBool(bool* value); + bool NextParamAsStr(char** valueBuf); + char* XmlNextValue(char* xml, const char* tag, int* valueLength); + const char* BoolToStr(bool value); + char* EncodeStr(const char* str); + void DecodeStr(char* str); public: XmlCommand(); virtual ~XmlCommand() {} virtual void Execute() = 0; void PrepareParams(); - void SetRequest(char* szRequest) { m_szRequest = szRequest; m_szRequestPtr = m_szRequest; } - void SetProtocol(XmlRpcProcessor::ERpcProtocol eProtocol) { m_eProtocol = eProtocol; } - void SetHttpMethod(XmlRpcProcessor::EHttpMethod eHttpMethod) { m_eHttpMethod = eHttpMethod; } - void SetUserAccess(XmlRpcProcessor::EUserAccess eUserAccess) { m_eUserAccess = eUserAccess; } - const char* GetResponse() { return m_StringBuilder.GetBuffer(); } - const char* GetCallbackFunc() { return m_szCallbackFunc; } - bool GetFault() { return m_bFault; } + void SetRequest(char* request) { m_request = request; m_requestPtr = m_request; } + void SetProtocol(XmlRpcProcessor::ERpcProtocol protocol) { m_protocol = protocol; } + void SetHttpMethod(XmlRpcProcessor::EHttpMethod httpMethod) { m_httpMethod = httpMethod; } + void SetUserAccess(XmlRpcProcessor::EUserAccess userAccess) { m_userAccess = userAccess; } + const char* GetResponse() { return m_stringBuilder.GetBuffer(); } + const char* GetCallbackFunc() { return m_callbackFunc; } + bool GetFault() { return m_fault; } }; #endif diff --git a/daemon/util/Log.cpp b/daemon/util/Log.cpp index c8dd8c82..d2c68513 100644 --- a/daemon/util/Log.cpp +++ b/daemon/util/Log.cpp @@ -61,20 +61,20 @@ void Log::Final() Log::Log() { - m_Messages.clear(); - m_iIDGen = 0; - m_bOptInit = false; - m_szLogFilename = NULL; - m_tLastWritten = 0; + m_messages.clear(); + m_idGen = 0; + m_optInit = false; + m_logFilename = NULL; + m_lastWritten = 0; #ifdef DEBUG - m_bExtraDebug = Util::FileExists("extradebug"); + m_extraDebug = Util::FileExists("extradebug"); #endif } Log::~Log() { Clear(); - free(m_szLogFilename); + free(m_logFilename); } void Log::LogDebugInfo() @@ -83,20 +83,20 @@ void Log::LogDebugInfo() info("Dumping debug info to log"); info("--------------------------------------------"); - m_mutexDebug.Lock(); - for (Debuggables::iterator it = m_Debuggables.begin(); it != m_Debuggables.end(); it++) + m_debugMutex.Lock(); + for (Debuggables::iterator it = m_debuggables.begin(); it != m_debuggables.end(); it++) { - Debuggable* pDebuggable = *it; - pDebuggable->LogDebugInfo(); + Debuggable* debuggable = *it; + debuggable->LogDebugInfo(); } - m_mutexDebug.Unlock(); + m_debugMutex.Unlock(); info("--------------------------------------------"); } void Log::Filelog(const char* msg, ...) { - if (!m_szLogFilename) + if (!m_logFilename) { return; } @@ -111,49 +111,49 @@ void Log::Filelog(const char* msg, ...) time_t rawtime = time(NULL) + g_pOptions->GetTimeCorrection(); - char szTime[50]; + char time[50]; #ifdef HAVE_CTIME_R_3 - ctime_r(&rawtime, szTime, 50); + ctime_r(&rawtime, time, 50); #else - ctime_r(&rawtime, szTime); + ctime_r(&rawtime, time); #endif - szTime[50-1] = '\0'; - szTime[strlen(szTime) - 1] = '\0'; // trim LF + time[50-1] = '\0'; + time[strlen(time) - 1] = '\0'; // trim LF - if ((int)rawtime/86400 != (int)m_tLastWritten/86400 && g_pOptions->GetWriteLog() == Options::wlRotate) + if ((int)rawtime/86400 != (int)m_lastWritten/86400 && g_pOptions->GetWriteLog() == Options::wlRotate) { RotateLog(); } - m_tLastWritten = rawtime; + m_lastWritten = rawtime; - FILE* file = fopen(m_szLogFilename, FOPEN_ABP); + FILE* file = fopen(m_logFilename, FOPEN_ABP); if (file) { #ifdef WIN32 - unsigned long iProcessId = GetCurrentProcessId(); - unsigned long iThreadId = GetCurrentThreadId(); + unsigned long processId = GetCurrentProcessId(); + unsigned long threadId = GetCurrentThreadId(); #else - unsigned long iProcessId = (unsigned long)getpid(); - unsigned long iThreadId = (unsigned long)pthread_self(); + unsigned long processId = (unsigned long)getpid(); + unsigned long threadId = (unsigned long)pthread_self(); #endif #ifdef DEBUG - fprintf(file, "%s\t%lu\t%lu\t%s%s", szTime, iProcessId, iThreadId, tmp2, LINE_ENDING); + fprintf(file, "%s\t%lu\t%lu\t%s%s", time, processId, threadId, tmp2, LINE_ENDING); #else - fprintf(file, "%s\t%s%s", szTime, tmp2, LINE_ENDING); + fprintf(file, "%s\t%s%s", time, tmp2, LINE_ENDING); #endif fclose(file); } else { - perror(m_szLogFilename); + perror(m_logFilename); } } #ifdef DEBUG #undef debug #ifdef HAVE_VARIADIC_MACROS -void debug(const char* szFilename, const char* szFuncname, int iLineNr, const char* msg, ...) +void debug(const char* filename, const char* funcname, int lineNr, const char* msg, ...) #else void debug(const char* msg, ...) #endif @@ -168,37 +168,37 @@ void debug(const char* msg, ...) char tmp2[1024]; #ifdef HAVE_VARIADIC_MACROS - if (szFuncname) + if (funcname) { - snprintf(tmp2, 1024, "%s (%s:%i:%s)", tmp1, Util::BaseFileName(szFilename), iLineNr, szFuncname); + snprintf(tmp2, 1024, "%s (%s:%i:%s)", tmp1, Util::BaseFileName(filename), lineNr, funcname); } else { - snprintf(tmp2, 1024, "%s (%s:%i)", tmp1, Util::BaseFileName(szFilename), iLineNr); + snprintf(tmp2, 1024, "%s (%s:%i)", tmp1, Util::BaseFileName(filename), lineNr); } #else snprintf(tmp2, 1024, "%s", tmp1); #endif tmp2[1024-1] = '\0'; - g_pLog->m_mutexLog.Lock(); + g_pLog->m_logMutex.Lock(); - if (!g_pOptions && g_pLog->m_bExtraDebug) + if (!g_pOptions && g_pLog->m_extraDebug) { printf("%s\n", tmp2); } - Options::EMessageTarget eMessageTarget = g_pOptions ? g_pOptions->GetDebugTarget() : Options::mtScreen; - if (eMessageTarget == Options::mtScreen || eMessageTarget == Options::mtBoth) + Options::EMessageTarget messageTarget = g_pOptions ? g_pOptions->GetDebugTarget() : Options::mtScreen; + if (messageTarget == Options::mtScreen || messageTarget == Options::mtBoth) { g_pLog->AddMessage(Message::mkDebug, tmp2); } - if (eMessageTarget == Options::mtLog || eMessageTarget == Options::mtBoth) + if (messageTarget == Options::mtLog || messageTarget == Options::mtBoth) { g_pLog->Filelog("DEBUG\t%s", tmp2); } - g_pLog->m_mutexLog.Unlock(); + g_pLog->m_logMutex.Unlock(); } #endif @@ -212,19 +212,19 @@ void error(const char* msg, ...) tmp2[1024-1] = '\0'; va_end(ap); - g_pLog->m_mutexLog.Lock(); + g_pLog->m_logMutex.Lock(); - Options::EMessageTarget eMessageTarget = g_pOptions ? g_pOptions->GetErrorTarget() : Options::mtBoth; - if (eMessageTarget == Options::mtScreen || eMessageTarget == Options::mtBoth) + Options::EMessageTarget messageTarget = g_pOptions ? g_pOptions->GetErrorTarget() : Options::mtBoth; + if (messageTarget == Options::mtScreen || messageTarget == Options::mtBoth) { g_pLog->AddMessage(Message::mkError, tmp2); } - if (eMessageTarget == Options::mtLog || eMessageTarget == Options::mtBoth) + if (messageTarget == Options::mtLog || messageTarget == Options::mtBoth) { g_pLog->Filelog("ERROR\t%s", tmp2); } - g_pLog->m_mutexLog.Unlock(); + g_pLog->m_logMutex.Unlock(); } void warn(const char* msg, ...) @@ -237,19 +237,19 @@ void warn(const char* msg, ...) tmp2[1024-1] = '\0'; va_end(ap); - g_pLog->m_mutexLog.Lock(); + g_pLog->m_logMutex.Lock(); - Options::EMessageTarget eMessageTarget = g_pOptions ? g_pOptions->GetWarningTarget() : Options::mtScreen; - if (eMessageTarget == Options::mtScreen || eMessageTarget == Options::mtBoth) + Options::EMessageTarget messageTarget = g_pOptions ? g_pOptions->GetWarningTarget() : Options::mtScreen; + if (messageTarget == Options::mtScreen || messageTarget == Options::mtBoth) { g_pLog->AddMessage(Message::mkWarning, tmp2); } - if (eMessageTarget == Options::mtLog || eMessageTarget == Options::mtBoth) + if (messageTarget == Options::mtLog || messageTarget == Options::mtBoth) { g_pLog->Filelog("WARNING\t%s", tmp2); } - g_pLog->m_mutexLog.Unlock(); + g_pLog->m_logMutex.Unlock(); } void info(const char* msg, ...) @@ -262,19 +262,19 @@ void info(const char* msg, ...) tmp2[1024-1] = '\0'; va_end(ap); - g_pLog->m_mutexLog.Lock(); + g_pLog->m_logMutex.Lock(); - Options::EMessageTarget eMessageTarget = g_pOptions ? g_pOptions->GetInfoTarget() : Options::mtScreen; - if (eMessageTarget == Options::mtScreen || eMessageTarget == Options::mtBoth) + Options::EMessageTarget messageTarget = g_pOptions ? g_pOptions->GetInfoTarget() : Options::mtScreen; + if (messageTarget == Options::mtScreen || messageTarget == Options::mtBoth) { g_pLog->AddMessage(Message::mkInfo, tmp2); } - if (eMessageTarget == Options::mtLog || eMessageTarget == Options::mtBoth) + if (messageTarget == Options::mtLog || messageTarget == Options::mtBoth) { g_pLog->Filelog("INFO\t%s", tmp2); } - g_pLog->m_mutexLog.Unlock(); + g_pLog->m_logMutex.Unlock(); } void detail(const char* msg, ...) @@ -287,42 +287,42 @@ void detail(const char* msg, ...) tmp2[1024-1] = '\0'; va_end(ap); - g_pLog->m_mutexLog.Lock(); + g_pLog->m_logMutex.Lock(); - Options::EMessageTarget eMessageTarget = g_pOptions ? g_pOptions->GetDetailTarget() : Options::mtScreen; - if (eMessageTarget == Options::mtScreen || eMessageTarget == Options::mtBoth) + Options::EMessageTarget messageTarget = g_pOptions ? g_pOptions->GetDetailTarget() : Options::mtScreen; + if (messageTarget == Options::mtScreen || messageTarget == Options::mtBoth) { g_pLog->AddMessage(Message::mkDetail, tmp2); } - if (eMessageTarget == Options::mtLog || eMessageTarget == Options::mtBoth) + if (messageTarget == Options::mtLog || messageTarget == Options::mtBoth) { g_pLog->Filelog("DETAIL\t%s", tmp2); } - g_pLog->m_mutexLog.Unlock(); + g_pLog->m_logMutex.Unlock(); } //************************************************************ // Message -Message::Message(unsigned int iID, EKind eKind, time_t tTime, const char* szText) +Message::Message(unsigned int id, EKind kind, time_t time, const char* text) { - m_iID = iID; - m_eKind = eKind; - m_tTime = tTime; - if (szText) + m_id = id; + m_kind = kind; + m_time = time; + if (text) { - m_szText = strdup(szText); + m_text = strdup(text); } else { - m_szText = NULL; + m_text = NULL; } } Message::~ Message() { - free(m_szText); + free(m_text); } MessageList::~MessageList() @@ -341,36 +341,36 @@ void MessageList::Clear() void Log::Clear() { - m_mutexLog.Lock(); - m_Messages.Clear(); - m_mutexLog.Unlock(); + m_logMutex.Lock(); + m_messages.Clear(); + m_logMutex.Unlock(); } -void Log::AddMessage(Message::EKind eKind, const char * szText) +void Log::AddMessage(Message::EKind kind, const char * text) { - Message* pMessage = new Message(++m_iIDGen, eKind, time(NULL), szText); - m_Messages.push_back(pMessage); + Message* message = new Message(++m_idGen, kind, time(NULL), text); + m_messages.push_back(message); - if (m_bOptInit && g_pOptions) + if (m_optInit && g_pOptions) { - while (m_Messages.size() > (unsigned int)g_pOptions->GetLogBufferSize()) + while (m_messages.size() > (unsigned int)g_pOptions->GetLogBufferSize()) { - Message* pMessage = m_Messages.front(); - delete pMessage; - m_Messages.pop_front(); + Message* message = m_messages.front(); + delete message; + m_messages.pop_front(); } } } MessageList* Log::LockMessages() { - m_mutexLog.Lock(); - return &m_Messages; + m_logMutex.Lock(); + return &m_messages; } void Log::UnlockMessages() { - m_mutexLog.Unlock(); + m_logMutex.Unlock(); } void Log::ResetLog() @@ -380,77 +380,77 @@ void Log::ResetLog() void Log::RotateLog() { - char szDirectory[1024]; - strncpy(szDirectory, g_pOptions->GetLogFile(), 1024); - szDirectory[1024-1] = '\0'; + char directory[1024]; + strncpy(directory, g_pOptions->GetLogFile(), 1024); + directory[1024-1] = '\0'; // split the full filename into path, basename and extension - char* szBaseName = Util::BaseFileName(szDirectory); - if (szBaseName > szDirectory) + char* baseName = Util::BaseFileName(directory); + if (baseName > directory) { - szBaseName[-1] = '\0'; + baseName[-1] = '\0'; } - char szBaseExt[250]; - char* szExt = strrchr(szBaseName, '.'); - if (szExt && szExt > szBaseName) + char baseExt[250]; + char* ext = strrchr(baseName, '.'); + if (ext && ext > baseName) { - strncpy(szBaseExt, szExt, 250); - szBaseExt[250-1] = '\0'; - szExt[0] = '\0'; + strncpy(baseExt, ext, 250); + baseExt[250-1] = '\0'; + ext[0] = '\0'; } else { - szBaseExt[0] = '\0'; + baseExt[0] = '\0'; } - char szFileMask[1024]; - snprintf(szFileMask, 1024, "%s-####-##-##%s", szBaseName, szBaseExt); - szFileMask[1024-1] = '\0'; + char fileMask[1024]; + snprintf(fileMask, 1024, "%s-####-##-##%s", baseName, baseExt); + fileMask[1024-1] = '\0'; - time_t tCurTime = time(NULL) + g_pOptions->GetTimeCorrection(); - int iCurDay = (int)tCurTime / 86400; - char szFullFilename[1024]; + time_t curTime = time(NULL) + g_pOptions->GetTimeCorrection(); + int curDay = (int)curTime / 86400; + char fullFilename[1024]; - WildMask mask(szFileMask, true); - DirBrowser dir(szDirectory); + WildMask mask(fileMask, true); + DirBrowser dir(directory); while (const char* filename = dir.Next()) { if (mask.Match(filename)) { - snprintf(szFullFilename, 1024, "%s%c%s", szDirectory, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + snprintf(fullFilename, 1024, "%s%c%s", directory, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_year = atoi(filename + mask.GetMatchStart(0)) - 1900; tm.tm_mon = atoi(filename + mask.GetMatchStart(1)) - 1; tm.tm_mday = atoi(filename + mask.GetMatchStart(2)); - time_t tFileTime = Util::Timegm(&tm); - int iFileDay = (int)tFileTime / 86400; + time_t fileTime = Util::Timegm(&tm); + int fileDay = (int)fileTime / 86400; - if (iFileDay <= iCurDay - g_pOptions->GetRotateLog()) + if (fileDay <= curDay - g_pOptions->GetRotateLog()) { - char szMessage[1024]; - snprintf(szMessage, 1024, "Deleting old log-file %s\n", filename); - szMessage[1024-1] = '\0'; - g_pLog->AddMessage(Message::mkInfo, szMessage); + char message[1024]; + snprintf(message, 1024, "Deleting old log-file %s\n", filename); + message[1024-1] = '\0'; + g_pLog->AddMessage(Message::mkInfo, message); - remove(szFullFilename); + remove(fullFilename); } } } struct tm tm; - gmtime_r(&tCurTime, &tm); - snprintf(szFullFilename, 1024, "%s%c%s-%i-%.2i-%.2i%s", szDirectory, PATH_SEPARATOR, - szBaseName, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, szBaseExt); - szFullFilename[1024-1] = '\0'; + gmtime_r(&curTime, &tm); + snprintf(fullFilename, 1024, "%s%c%s-%i-%.2i-%.2i%s", directory, PATH_SEPARATOR, + baseName, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, baseExt); + fullFilename[1024-1] = '\0'; - free(m_szLogFilename); - m_szLogFilename = strdup(szFullFilename); + free(m_logFilename); + m_logFilename = strdup(fullFilename); #ifdef WIN32 - WebUtil::Utf8ToAnsi(m_szLogFilename, strlen(m_szLogFilename) + 1); + WebUtil::Utf8ToAnsi(m_logFilename, strlen(m_logFilename) + 1); #endif } @@ -465,13 +465,13 @@ void Log::RotateLog() */ void Log::InitOptions() { - const char* szMessageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL"}; + const char* messageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL"}; if (g_pOptions->GetWriteLog() != Options::wlNone && g_pOptions->GetLogFile()) { - m_szLogFilename = strdup(g_pOptions->GetLogFile()); + m_logFilename = strdup(g_pOptions->GetLogFile()); #ifdef WIN32 - WebUtil::Utf8ToAnsi(m_szLogFilename, strlen(m_szLogFilename) + 1); + WebUtil::Utf8ToAnsi(m_logFilename, strlen(m_logFilename) + 1); #endif if (g_pOptions->GetServerMode() && g_pOptions->GetWriteLog() == Options::wlReset) @@ -480,61 +480,61 @@ void Log::InitOptions() } } - m_iIDGen = 0; + m_idGen = 0; - for (unsigned int i = 0; i < m_Messages.size(); ) + for (unsigned int i = 0; i < m_messages.size(); ) { - Message* pMessage = m_Messages.at(i); - Options::EMessageTarget eTarget = Options::mtNone; - switch (pMessage->GetKind()) + Message* message = m_messages.at(i); + Options::EMessageTarget target = Options::mtNone; + switch (message->GetKind()) { case Message::mkDebug: - eTarget = g_pOptions->GetDebugTarget(); + target = g_pOptions->GetDebugTarget(); break; case Message::mkDetail: - eTarget = g_pOptions->GetDetailTarget(); + target = g_pOptions->GetDetailTarget(); break; case Message::mkInfo: - eTarget = g_pOptions->GetInfoTarget(); + target = g_pOptions->GetInfoTarget(); break; case Message::mkWarning: - eTarget = g_pOptions->GetWarningTarget(); + target = g_pOptions->GetWarningTarget(); break; case Message::mkError: - eTarget = g_pOptions->GetErrorTarget(); + target = g_pOptions->GetErrorTarget(); break; } - if (eTarget == Options::mtLog || eTarget == Options::mtBoth) + if (target == Options::mtLog || target == Options::mtBoth) { - Filelog("%s\t%s", szMessageType[pMessage->GetKind()], pMessage->GetText()); + Filelog("%s\t%s", messageType[message->GetKind()], message->GetText()); } - if (eTarget == Options::mtLog || eTarget == Options::mtNone) + if (target == Options::mtLog || target == Options::mtNone) { - delete pMessage; - m_Messages.erase(m_Messages.begin() + i); + delete message; + m_messages.erase(m_messages.begin() + i); } else { - pMessage->m_iID = ++m_iIDGen; + message->m_id = ++m_idGen; i++; } } - m_bOptInit = true; + m_optInit = true; } -void Log::RegisterDebuggable(Debuggable* pDebuggable) +void Log::RegisterDebuggable(Debuggable* debuggable) { - m_mutexDebug.Lock(); - m_Debuggables.push_back(pDebuggable); - m_mutexDebug.Unlock(); + m_debugMutex.Lock(); + m_debuggables.push_back(debuggable); + m_debugMutex.Unlock(); } -void Log::UnregisterDebuggable(Debuggable* pDebuggable) +void Log::UnregisterDebuggable(Debuggable* debuggable) { - m_mutexDebug.Lock(); - m_Debuggables.remove(pDebuggable); - m_mutexDebug.Unlock(); + m_debugMutex.Lock(); + m_debuggables.remove(debuggable); + m_debugMutex.Unlock(); } diff --git a/daemon/util/Log.h b/daemon/util/Log.h index 165f26c1..85019450 100644 --- a/daemon/util/Log.h +++ b/daemon/util/Log.h @@ -40,7 +40,7 @@ void detail(const char* msg, ...); #ifdef DEBUG #ifdef HAVE_VARIADIC_MACROS - void debug(const char* szFilename, const char* szFuncname, int iLineNr, const char* msg, ...); + void debug(const char* filename, const char* funcname, int lineNr, const char* msg, ...); #else void debug(const char* msg, ...); #endif @@ -59,20 +59,20 @@ public: }; private: - unsigned int m_iID; - EKind m_eKind; - time_t m_tTime; - char* m_szText; + unsigned int m_id; + EKind m_kind; + time_t m_time; + char* m_text; friend class Log; public: - Message(unsigned int iID, EKind eKind, time_t tTime, const char* szText); + Message(unsigned int id, EKind kind, time_t time, const char* text); ~Message(); - unsigned int GetID() { return m_iID; } - EKind GetKind() { return m_eKind; } - time_t GetTime() { return m_tTime; } - const char* GetText() { return m_szText; } + unsigned int GetID() { return m_id; } + EKind GetKind() { return m_kind; } + time_t GetTime() { return m_time; } + const char* GetText() { return m_text; } }; typedef std::deque MessageListBase; @@ -97,22 +97,22 @@ public: typedef std::list Debuggables; private: - Mutex m_mutexLog; - MessageList m_Messages; - Debuggables m_Debuggables; - Mutex m_mutexDebug; - char* m_szLogFilename; - unsigned int m_iIDGen; - time_t m_tLastWritten; - bool m_bOptInit; + Mutex m_logMutex; + MessageList m_messages; + Debuggables m_debuggables; + Mutex m_debugMutex; + char* m_logFilename; + unsigned int m_idGen; + time_t m_lastWritten; + bool m_optInit; #ifdef DEBUG - bool m_bExtraDebug; + bool m_extraDebug; #endif Log(); ~Log(); void Filelog(const char* msg, ...); - void AddMessage(Message::EKind eKind, const char* szText); + void AddMessage(Message::EKind kind, const char* text); void RotateLog(); friend void error(const char* msg, ...); @@ -121,7 +121,7 @@ private: friend void detail(const char* msg, ...); #ifdef DEBUG #ifdef HAVE_VARIADIC_MACROS - friend void debug(const char* szFilename, const char* szFuncname, int iLineNr, const char* msg, ...); + friend void debug(const char* filename, const char* funcname, int lineNr, const char* msg, ...); #else friend void debug(const char* msg, ...); #endif @@ -135,8 +135,8 @@ public: void Clear(); void ResetLog(); void InitOptions(); - void RegisterDebuggable(Debuggable* pDebuggable); - void UnregisterDebuggable(Debuggable* pDebuggable); + void RegisterDebuggable(Debuggable* debuggable); + void UnregisterDebuggable(Debuggable* debuggable); void LogDebugInfo(); }; diff --git a/daemon/util/Observer.cpp b/daemon/util/Observer.cpp index 0b7af324..657b8a93 100644 --- a/daemon/util/Observer.cpp +++ b/daemon/util/Observer.cpp @@ -37,26 +37,26 @@ Subject::Subject() { - m_Observers.clear(); + m_observers.clear(); } -void Subject::Attach(Observer* pObserver) +void Subject::Attach(Observer* observer) { - m_Observers.push_back(pObserver); + m_observers.push_back(observer); } -void Subject::Detach(Observer* pObserver) +void Subject::Detach(Observer* observer) { - m_Observers.remove(pObserver); + m_observers.remove(observer); } -void Subject::Notify(void* pAspect) +void Subject::Notify(void* aspect) { debug("Notifying observers"); - for (std::list::iterator it = m_Observers.begin(); it != m_Observers.end(); it++) + for (std::list::iterator it = m_observers.begin(); it != m_observers.end(); it++) { Observer* Observer = *it; - Observer->Update(this, pAspect); + Observer->Update(this, aspect); } } diff --git a/daemon/util/Observer.h b/daemon/util/Observer.h index 92b24cae..c3ea3084 100644 --- a/daemon/util/Observer.h +++ b/daemon/util/Observer.h @@ -34,19 +34,19 @@ class Observer; class Subject { private: - std::list m_Observers; + std::list m_observers; public: Subject(); - void Attach(Observer* pObserver); - void Detach(Observer* pObserver); - void Notify(void* pAspect); + void Attach(Observer* observer); + void Detach(Observer* observer); + void Notify(void* aspect); }; class Observer { protected: - virtual void Update(Subject* pCaller, void* pAspect) = 0; + virtual void Update(Subject* caller, void* aspect) = 0; friend class Subject; }; diff --git a/daemon/util/Script.cpp b/daemon/util/Script.cpp index fabab014..ea4ef1e3 100644 --- a/daemon/util/Script.cpp +++ b/daemon/util/Script.cpp @@ -58,8 +58,8 @@ extern char** environ; extern char* (*g_szEnvironmentVariables)[]; -ScriptController::RunningScripts ScriptController::m_RunningScripts; -Mutex ScriptController::m_mutexRunning; +ScriptController::RunningScripts ScriptController::m_runningScripts; +Mutex ScriptController::m_runningMutex; #ifndef WIN32 #define CHILD_WATCHDOG 1 @@ -92,8 +92,8 @@ public: void ChildWatchDog::Run() { static const int WAIT_SECONDS = 60; - time_t tStart = time(NULL); - while (!IsStopped() && (time(NULL) - tStart) < WAIT_SECONDS) + time_t start = time(NULL); + while (!IsStopped() && (time(NULL) - start) < WAIT_SECONDS) { usleep(10 * 1000); } @@ -129,21 +129,21 @@ void EnvironmentStrings::InitFromCurrentProcess() { for (int i = 0; (*g_szEnvironmentVariables)[i]; i++) { - char* szVar = (*g_szEnvironmentVariables)[i]; + char* var = (*g_szEnvironmentVariables)[i]; // Ignore all env vars set by NZBGet. // This is to avoid the passing of env vars after program update (when NZBGet is // started from a script which was started by a previous instance of NZBGet). // Format: NZBXX_YYYY (XX are any two characters, YYYY are any number of any characters). - if (!(!strncmp(szVar, "NZB", 3) && strlen(szVar) > 5 && szVar[5] == '_')) + if (!(!strncmp(var, "NZB", 3) && strlen(var) > 5 && var[5] == '_')) { - Append(strdup(szVar)); + Append(strdup(var)); } } } -void EnvironmentStrings::Append(char* szString) +void EnvironmentStrings::Append(char* string) { - m_strings.push_back(szString); + m_strings.push_back(string); } #ifdef WIN32 @@ -153,24 +153,24 @@ void EnvironmentStrings::Append(char* szString) */ char* EnvironmentStrings::GetStrings() { - int iSize = 1; + int size = 1; for (Strings::iterator it = m_strings.begin(); it != m_strings.end(); it++) { - char* szVar = *it; - iSize += strlen(szVar) + 1; + char* var = *it; + size += strlen(var) + 1; } - char* szStrings = (char*)malloc(iSize); - char* szPtr = szStrings; + char* strings = (char*)malloc(size); + char* ptr = strings; for (Strings::iterator it = m_strings.begin(); it != m_strings.end(); it++) { - char* szVar = *it; - strcpy(szPtr, szVar); - szPtr += strlen(szVar) + 1; + char* var = *it; + strcpy(ptr, var); + ptr += strlen(var) + 1; } - *szPtr = '\0'; + *ptr = '\0'; - return szStrings; + return strings; } #else @@ -181,48 +181,48 @@ char* EnvironmentStrings::GetStrings() */ char** EnvironmentStrings::GetStrings() { - char** pStrings = (char**)malloc((m_strings.size() + 1) * sizeof(char*)); - char** pPtr = pStrings; + char** strings = (char**)malloc((m_strings.size() + 1) * sizeof(char*)); + char** ptr = strings; for (Strings::iterator it = m_strings.begin(); it != m_strings.end(); it++) { - char* szVar = *it; - *pPtr = szVar; - pPtr++; + char* var = *it; + *ptr = var; + ptr++; } - *pPtr = NULL; + *ptr = NULL; - return pStrings; + return strings; } #endif ScriptController::ScriptController() { - m_szScript = NULL; - m_szWorkingDir = NULL; - m_szArgs = NULL; - m_bFreeArgs = false; - m_szInfoName = NULL; - m_szLogPrefix = NULL; - m_bTerminated = false; - m_bDetached = false; + m_script = NULL; + m_workingDir = NULL; + m_args = NULL; + m_freeArgs = false; + m_infoName = NULL; + m_logPrefix = NULL; + m_terminated = false; + m_detached = false; m_hProcess = 0; ResetEnv(); - m_mutexRunning.Lock(); - m_RunningScripts.push_back(this); - m_mutexRunning.Unlock(); + m_runningMutex.Lock(); + m_runningScripts.push_back(this); + m_runningMutex.Unlock(); } ScriptController::~ScriptController() { - if (m_bFreeArgs) + if (m_freeArgs) { - for (const char** szArgPtr = m_szArgs; *szArgPtr; szArgPtr++) + for (const char** argPtr = m_args; *argPtr; argPtr++) { - free((char*)*szArgPtr); + free((char*)*argPtr); } - free(m_szArgs); + free(m_args); } UnregisterRunningScript(); @@ -230,13 +230,13 @@ ScriptController::~ScriptController() void ScriptController::UnregisterRunningScript() { - m_mutexRunning.Lock(); - RunningScripts::iterator it = std::find(m_RunningScripts.begin(), m_RunningScripts.end(), this); - if (it != m_RunningScripts.end()) + m_runningMutex.Lock(); + RunningScripts::iterator it = std::find(m_runningScripts.begin(), m_runningScripts.end(), this); + if (it != m_runningScripts.end()) { - m_RunningScripts.erase(it); + m_runningScripts.erase(it); } - m_mutexRunning.Unlock(); + m_runningMutex.Unlock(); } void ScriptController::ResetEnv() @@ -245,20 +245,20 @@ void ScriptController::ResetEnv() m_environmentStrings.InitFromCurrentProcess(); } -void ScriptController::SetEnvVar(const char* szName, const char* szValue) +void ScriptController::SetEnvVar(const char* name, const char* value) { - int iLen = strlen(szName) + strlen(szValue) + 2; - char* szVar = (char*)malloc(iLen); - snprintf(szVar, iLen, "%s=%s", szName, szValue); - m_environmentStrings.Append(szVar); + int len = strlen(name) + strlen(value) + 2; + char* var = (char*)malloc(len); + snprintf(var, len, "%s=%s", name, value); + m_environmentStrings.Append(var); } -void ScriptController::SetIntEnvVar(const char* szName, int iValue) +void ScriptController::SetIntEnvVar(const char* name, int value) { - char szValue[1024]; - snprintf(szValue, 10, "%i", iValue); - szValue[1024-1] = '\0'; - SetEnvVar(szName, szValue); + char strValue[1024]; + snprintf(strValue, 10, "%i", value); + strValue[1024-1] = '\0'; + SetEnvVar(name, strValue); } /** @@ -266,103 +266,103 @@ void ScriptController::SetIntEnvVar(const char* szName, int iValue) * are processed. The prefix is then stripped from the names. * If szStripPrefix is NULL, all options are processed; without stripping. */ -void ScriptController::PrepareEnvOptions(const char* szStripPrefix) +void ScriptController::PrepareEnvOptions(const char* stripPrefix) { - int iPrefixLen = szStripPrefix ? strlen(szStripPrefix) : 0; + int prefixLen = stripPrefix ? strlen(stripPrefix) : 0; - Options::OptEntries* pOptEntries = g_pOptions->LockOptEntries(); + Options::OptEntries* optEntries = g_pOptions->LockOptEntries(); - for (Options::OptEntries::iterator it = pOptEntries->begin(); it != pOptEntries->end(); it++) + for (Options::OptEntries::iterator it = optEntries->begin(); it != optEntries->end(); it++) { - Options::OptEntry* pOptEntry = *it; + Options::OptEntry* optEntry = *it; - if (szStripPrefix && !strncmp(pOptEntry->GetName(), szStripPrefix, iPrefixLen) && (int)strlen(pOptEntry->GetName()) > iPrefixLen) + if (stripPrefix && !strncmp(optEntry->GetName(), stripPrefix, prefixLen) && (int)strlen(optEntry->GetName()) > prefixLen) { - SetEnvVarSpecial("NZBPO", pOptEntry->GetName() + iPrefixLen, pOptEntry->GetValue()); + SetEnvVarSpecial("NZBPO", optEntry->GetName() + prefixLen, optEntry->GetValue()); } - else if (!szStripPrefix) + else if (!stripPrefix) { - SetEnvVarSpecial("NZBOP", pOptEntry->GetName(), pOptEntry->GetValue()); + SetEnvVarSpecial("NZBOP", optEntry->GetName(), optEntry->GetValue()); } } g_pOptions->UnlockOptEntries(); } -void ScriptController::SetEnvVarSpecial(const char* szPrefix, const char* szName, const char* szValue) +void ScriptController::SetEnvVarSpecial(const char* prefix, const char* name, const char* value) { - char szVarname[1024]; - snprintf(szVarname, sizeof(szVarname), "%s_%s", szPrefix, szName); - szVarname[1024-1] = '\0'; + char varname[1024]; + snprintf(varname, sizeof(varname), "%s_%s", prefix, name); + varname[1024-1] = '\0'; // Original name - SetEnvVar(szVarname, szValue); + SetEnvVar(varname, value); - char szNormVarname[1024]; - strncpy(szNormVarname, szVarname, sizeof(szVarname)); - szNormVarname[1024-1] = '\0'; + char normVarname[1024]; + strncpy(normVarname, varname, sizeof(varname)); + normVarname[1024-1] = '\0'; // Replace special characters with "_" and convert to upper case - for (char* szPtr = szNormVarname; *szPtr; szPtr++) + for (char* ptr = normVarname; *ptr; ptr++) { - if (strchr(".:*!\"$%&/()=`+~#'{}[]@- ", *szPtr)) *szPtr = '_'; - *szPtr = toupper(*szPtr); + if (strchr(".:*!\"$%&/()=`+~#'{}[]@- ", *ptr)) *ptr = '_'; + *ptr = toupper(*ptr); } // Another env var with normalized name (replaced special chars and converted to upper case) - if (strcmp(szVarname, szNormVarname)) + if (strcmp(varname, normVarname)) { - SetEnvVar(szNormVarname, szValue); + SetEnvVar(normVarname, value); } } void ScriptController::PrepareArgs() { #ifdef WIN32 - if (!m_szArgs) + if (!m_args) { // Special support for script languages: // automatically find the app registered for this extension and run it - const char* szExtension = strrchr(GetScript(), '.'); - if (szExtension && strcasecmp(szExtension, ".exe") && strcasecmp(szExtension, ".bat") && strcasecmp(szExtension, ".cmd")) + const char* extension = strrchr(GetScript(), '.'); + if (extension && strcasecmp(extension, ".exe") && strcasecmp(extension, ".bat") && strcasecmp(extension, ".cmd")) { - debug("Looking for associated program for %s", szExtension); - char szCommand[512]; - int iBufLen = 512-1; - if (Util::RegReadStr(HKEY_CLASSES_ROOT, szExtension, NULL, szCommand, &iBufLen)) + debug("Looking for associated program for %s", extension); + char command[512]; + int bufLen = 512-1; + if (Util::RegReadStr(HKEY_CLASSES_ROOT, extension, NULL, command, &bufLen)) { - szCommand[iBufLen] = '\0'; - debug("Extension: %s", szCommand); + command[bufLen] = '\0'; + debug("Extension: %s", command); - char szRegPath[512]; - snprintf(szRegPath, 512, "%s\\shell\\open\\command", szCommand); - szRegPath[512-1] = '\0'; + char regPath[512]; + snprintf(regPath, 512, "%s\\shell\\open\\command", command); + regPath[512-1] = '\0'; - iBufLen = 512-1; - if (Util::RegReadStr(HKEY_CLASSES_ROOT, szRegPath, NULL, szCommand, &iBufLen)) + bufLen = 512-1; + if (Util::RegReadStr(HKEY_CLASSES_ROOT, regPath, NULL, command, &bufLen)) { - szCommand[iBufLen] = '\0'; - debug("Command: %s", szCommand); + command[bufLen] = '\0'; + debug("Command: %s", command); - DWORD_PTR pArgs[] = { (DWORD_PTR)GetScript(), (DWORD_PTR)0 }; - if (FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, szCommand, 0, 0, - m_szCmdLine, sizeof(m_szCmdLine), (va_list*)pArgs)) + DWORD_PTR args[] = { (DWORD_PTR)GetScript(), (DWORD_PTR)0 }; + if (FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, command, 0, 0, + m_cmdLine, sizeof(m_cmdLine), (va_list*)args)) { - debug("CmdLine: %s", m_szCmdLine); + debug("CmdLine: %s", m_cmdLine); return; } } } - warn("Could not found associated program for %s. Trying to execute %s directly", szExtension, Util::BaseFileName(GetScript())); + warn("Could not found associated program for %s. Trying to execute %s directly", extension, Util::BaseFileName(GetScript())); } } #endif - if (!m_szArgs) + if (!m_args) { - m_szStdArgs[0] = GetScript(); - m_szStdArgs[1] = NULL; - SetArgs(m_szStdArgs, false); + m_stdArgs[0] = GetScript(); + m_stdArgs[1] = NULL; + SetArgs(m_stdArgs, false); } } @@ -371,34 +371,34 @@ int ScriptController::Execute() PrepareEnvOptions(NULL); PrepareArgs(); - int iExitCode = 0; + int exitCode = 0; int pipein; #ifdef CHILD_WATCHDOG - bool bChildConfirmed = false; - while (!bChildConfirmed && !m_bTerminated) + bool childConfirmed = false; + while (!childConfirmed && !m_terminated) { #endif #ifdef WIN32 // build command line - char* szCmdLine = NULL; - if (m_szArgs) + char* cmdLine = NULL; + if (m_args) { - char szCmdLineBuf[2048]; - int iUsedLen = 0; - for (const char** szArgPtr = m_szArgs; *szArgPtr; szArgPtr++) + char cmdLineBuf[2048]; + int usedLen = 0; + for (const char** argPtr = m_args; *argPtr; argPtr++) { - snprintf(szCmdLineBuf + iUsedLen, 2048 - iUsedLen, "\"%s\" ", *szArgPtr); - iUsedLen += strlen(*szArgPtr) + 3; + snprintf(cmdLineBuf + usedLen, 2048 - usedLen, "\"%s\" ", *argPtr); + usedLen += strlen(*argPtr) + 3; } - szCmdLineBuf[iUsedLen < 2048 ? iUsedLen - 1 : 2048 - 1] = '\0'; - szCmdLine = szCmdLineBuf; + cmdLineBuf[usedLen < 2048 ? usedLen - 1 : 2048 - 1] = '\0'; + cmdLine = cmdLineBuf; } else { - szCmdLine = m_szCmdLine; + cmdLine = m_cmdLine; } // create pipes to write and read data @@ -423,31 +423,31 @@ int ScriptController::Execute() PROCESS_INFORMATION ProcessInfo; memset(&ProcessInfo, 0, sizeof(ProcessInfo)); - char* szEnvironmentStrings = m_environmentStrings.GetStrings(); + char* environmentStrings = m_environmentStrings.GetStrings(); - BOOL bOK = CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, szEnvironmentStrings, m_szWorkingDir, &StartupInfo, &ProcessInfo); - if (!bOK) + BOOL ok = CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, environmentStrings, m_workingDir, &StartupInfo, &ProcessInfo); + if (!ok) { DWORD dwErrCode = GetLastError(); - char szErrMsg[255]; - szErrMsg[255-1] = '\0'; - if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErrCode, 0, szErrMsg, 255, NULL)) + char errMsg[255]; + errMsg[255-1] = '\0'; + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErrCode, 0, errMsg, 255, NULL)) { - PrintMessage(Message::mkError, "Could not start %s: %s", m_szInfoName, szErrMsg); + PrintMessage(Message::mkError, "Could not start %s: %s", m_infoName, errMsg); } else { - PrintMessage(Message::mkError, "Could not start %s: error %i", m_szInfoName, dwErrCode); + PrintMessage(Message::mkError, "Could not start %s: error %i", m_infoName, dwErrCode); } - if (!Util::FileExists(m_szScript)) + if (!Util::FileExists(m_script)) { - PrintMessage(Message::mkError, "Could not find file %s", m_szScript); + PrintMessage(Message::mkError, "Could not find file %s", m_script); } - free(szEnvironmentStrings); + free(environmentStrings); return -1; } - free(szEnvironmentStrings); + free(environmentStrings); debug("Child Process-ID: %i", (int)ProcessInfo.dwProcessId); @@ -470,7 +470,7 @@ int ScriptController::Execute() return -1; } - char** pEnvironmentStrings = m_environmentStrings.GetStrings(); + char** environmentStrings = m_environmentStrings.GetStrings(); pipein = p[0]; pipeout = p[1]; @@ -480,8 +480,8 @@ int ScriptController::Execute() if (pid == -1) { - PrintMessage(Message::mkError, "Could not start %s: errno %i", m_szInfoName, errno); - free(pEnvironmentStrings); + PrintMessage(Message::mkError, "Could not start %s: errno %i", m_infoName, errno); + free(environmentStrings); return -1; } else if (pid == 0) @@ -505,21 +505,21 @@ int ScriptController::Execute() fflush(stdout); #endif - chdir(m_szWorkingDir); - environ = pEnvironmentStrings; - execvp(m_szScript, (char* const*)m_szArgs); + chdir(m_workingDir); + environ = environmentStrings; + execvp(m_script, (char* const*)m_args); if (errno == EACCES) { - fprintf(stdout, "[WARNING] Fixing permissions for %s\n", m_szScript); + fprintf(stdout, "[WARNING] Fixing permissions for %s\n", m_script); fflush(stdout); - Util::FixExecPermission(m_szScript); - execvp(m_szScript, (char* const*)m_szArgs); + Util::FixExecPermission(m_script); + execvp(m_script, (char* const*)m_args); } // NOTE: the text "[ERROR] Could not start " is checked later, // by changing adjust the dependent code below. - fprintf(stdout, "[ERROR] Could not start %s: %s", m_szScript, strerror(errno)); + fprintf(stdout, "[ERROR] Could not start %s: %s", m_script, strerror(errno)); fflush(stdout); _exit(254); } @@ -528,7 +528,7 @@ int ScriptController::Execute() debug("forked"); debug("Child Process-ID: %i", (int)pid); - free(pEnvironmentStrings); + free(environmentStrings); m_hProcess = pid; @@ -537,91 +537,91 @@ int ScriptController::Execute() #endif // open the read end - m_pReadpipe = fdopen(pipein, "r"); - if (!m_pReadpipe) + m_readpipe = fdopen(pipein, "r"); + if (!m_readpipe) { - PrintMessage(Message::mkError, "Could not open pipe to %s", m_szInfoName); + PrintMessage(Message::mkError, "Could not open pipe to %s", m_infoName); return -1; } #ifdef CHILD_WATCHDOG debug("Creating child watchdog"); - ChildWatchDog* pWatchDog = new ChildWatchDog(); - pWatchDog->SetAutoDestroy(false); - pWatchDog->SetProcessID(pid); - pWatchDog->Start(); + ChildWatchDog* watchDog = new ChildWatchDog(); + watchDog->SetAutoDestroy(false); + watchDog->SetProcessID(pid); + watchDog->Start(); #endif char* buf = (char*)malloc(10240); debug("Entering pipe-loop"); - bool bFirstLine = true; - bool bStartError = false; - while (!m_bTerminated && !m_bDetached && !feof(m_pReadpipe)) + bool firstLine = true; + bool startError = false; + while (!m_terminated && !m_detached && !feof(m_readpipe)) { - if (ReadLine(buf, 10240, m_pReadpipe) && m_pReadpipe) + if (ReadLine(buf, 10240, m_readpipe) && m_readpipe) { #ifdef CHILD_WATCHDOG - if (!bChildConfirmed) + if (!childConfirmed) { - bChildConfirmed = true; - pWatchDog->Stop(); + childConfirmed = true; + watchDog->Stop(); debug("Child confirmed"); continue; } #endif - if (bFirstLine && !strncmp(buf, "[ERROR] Could not start ", 24)) + if (firstLine && !strncmp(buf, "[ERROR] Could not start ", 24)) { - bStartError = true; + startError = true; } ProcessOutput(buf); - bFirstLine = false; + firstLine = false; } } debug("Exited pipe-loop"); #ifdef CHILD_WATCHDOG debug("Destroying WatchDog"); - if (!bChildConfirmed) + if (!childConfirmed) { - pWatchDog->Stop(); + watchDog->Stop(); } - while (pWatchDog->IsRunning()) + while (watchDog->IsRunning()) { usleep(5 * 1000); } - delete pWatchDog; + delete watchDog; #endif free(buf); - if (m_pReadpipe) + if (m_readpipe) { - fclose(m_pReadpipe); + fclose(m_readpipe); } - if (m_bTerminated && m_szInfoName) + if (m_terminated && m_infoName) { - warn("Interrupted %s", m_szInfoName); + warn("Interrupted %s", m_infoName); } - iExitCode = 0; + exitCode = 0; - if (!m_bTerminated && !m_bDetached) + if (!m_terminated && !m_detached) { #ifdef WIN32 WaitForSingleObject(m_hProcess, INFINITE); DWORD dExitCode = 0; GetExitCodeProcess(m_hProcess, &dExitCode); - iExitCode = dExitCode; + exitCode = dExitCode; #else - int iStatus = 0; - waitpid(m_hProcess, &iStatus, 0); - if (WIFEXITED(iStatus)) + int status = 0; + waitpid(m_hProcess, &status, 0); + if (WIFEXITED(status)) { - iExitCode = WEXITSTATUS(iStatus); - if (iExitCode == 254 && bStartError) + exitCode = WEXITSTATUS(status); + if (exitCode == 254 && startError) { - iExitCode = -1; + exitCode = -1; } } #endif @@ -631,19 +631,19 @@ int ScriptController::Execute() } // while (!bChildConfirmed && !m_bTerminated) #endif - debug("Exit code %i", iExitCode); + debug("Exit code %i", exitCode); - return iExitCode; + return exitCode; } void ScriptController::Terminate() { - debug("Stopping %s", m_szInfoName); - m_bTerminated = true; + debug("Stopping %s", m_infoName); + m_terminated = true; #ifdef WIN32 - BOOL bOK = TerminateProcess(m_hProcess, -1); - if (bOK) + BOOL ok = TerminateProcess(m_hProcess, -1); + if (ok) { // wait 60 seconds for process to terminate WaitForSingleObject(m_hProcess, 60 * 1000); @@ -652,7 +652,7 @@ void ScriptController::Terminate() { DWORD dExitCode = 0; GetExitCodeProcess(m_hProcess, &dExitCode); - bOK = dExitCode != STILL_ACTIVE; + ok = dExitCode != STILL_ACTIVE; } #else pid_t hKillProcess = m_hProcess; @@ -661,136 +661,136 @@ void ScriptController::Terminate() // if the child process has its own group (setsid() was successful), kill the whole group hKillProcess = -hKillProcess; } - bool bOK = hKillProcess && kill(hKillProcess, SIGKILL) == 0; + bool ok = hKillProcess && kill(hKillProcess, SIGKILL) == 0; #endif - if (bOK) + if (ok) { - debug("Terminated %s", m_szInfoName); + debug("Terminated %s", m_infoName); } else { - error("Could not terminate %s", m_szInfoName); + error("Could not terminate %s", m_infoName); } - debug("Stopped %s", m_szInfoName); + debug("Stopped %s", m_infoName); } void ScriptController::TerminateAll() { - m_mutexRunning.Lock(); - for (RunningScripts::iterator it = m_RunningScripts.begin(); it != m_RunningScripts.end(); it++) + m_runningMutex.Lock(); + for (RunningScripts::iterator it = m_runningScripts.begin(); it != m_runningScripts.end(); it++) { - ScriptController* pScript = *it; - if (pScript->m_hProcess && !pScript->m_bDetached) + ScriptController* script = *it; + if (script->m_hProcess && !script->m_detached) { - pScript->Terminate(); + script->Terminate(); } } - m_mutexRunning.Unlock(); + m_runningMutex.Unlock(); } void ScriptController::Detach() { - debug("Detaching %s", m_szInfoName); - m_bDetached = true; - FILE* pReadpipe = m_pReadpipe; - m_pReadpipe = NULL; - fclose(pReadpipe); + debug("Detaching %s", m_infoName); + m_detached = true; + FILE* readpipe = m_readpipe; + m_readpipe = NULL; + fclose(readpipe); } void ScriptController::Resume() { - m_bTerminated = false; - m_bDetached = false; + m_terminated = false; + m_detached = false; m_hProcess = 0; } -bool ScriptController::ReadLine(char* szBuf, int iBufSize, FILE* pStream) +bool ScriptController::ReadLine(char* buf, int bufSize, FILE* stream) { - return fgets(szBuf, iBufSize, pStream); + return fgets(buf, bufSize, stream); } -void ScriptController::ProcessOutput(char* szText) +void ScriptController::ProcessOutput(char* text) { debug("Processing output received from script"); - for (char* pend = szText + strlen(szText) - 1; pend >= szText && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; + for (char* pend = text + strlen(text) - 1; pend >= text && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; - if (szText[0] == '\0') + if (text[0] == '\0') { // skip empty lines return; } - if (!strncmp(szText, "[INFO] ", 7)) + if (!strncmp(text, "[INFO] ", 7)) { - PrintMessage(Message::mkInfo, "%s", szText + 7); + PrintMessage(Message::mkInfo, "%s", text + 7); } - else if (!strncmp(szText, "[WARNING] ", 10)) + else if (!strncmp(text, "[WARNING] ", 10)) { - PrintMessage(Message::mkWarning, "%s", szText + 10); + PrintMessage(Message::mkWarning, "%s", text + 10); } - else if (!strncmp(szText, "[ERROR] ", 8)) + else if (!strncmp(text, "[ERROR] ", 8)) { - PrintMessage(Message::mkError, "%s", szText + 8); + PrintMessage(Message::mkError, "%s", text + 8); } - else if (!strncmp(szText, "[DETAIL] ", 9)) + else if (!strncmp(text, "[DETAIL] ", 9)) { - PrintMessage(Message::mkDetail, "%s", szText + 9); + PrintMessage(Message::mkDetail, "%s", text + 9); } - else if (!strncmp(szText, "[DEBUG] ", 8)) + else if (!strncmp(text, "[DEBUG] ", 8)) { - PrintMessage(Message::mkDebug, "%s", szText + 8); + PrintMessage(Message::mkDebug, "%s", text + 8); } else { - PrintMessage(Message::mkInfo, "%s", szText); + PrintMessage(Message::mkInfo, "%s", text); } debug("Processing output received from script - completed"); } -void ScriptController::AddMessage(Message::EKind eKind, const char* szText) +void ScriptController::AddMessage(Message::EKind kind, const char* text) { - switch (eKind) + switch (kind) { case Message::mkDetail: - detail("%s", szText); + detail("%s", text); break; case Message::mkInfo: - info("%s", szText); + info("%s", text); break; case Message::mkWarning: - warn("%s", szText); + warn("%s", text); break; case Message::mkError: - error("%s", szText); + error("%s", text); break; case Message::mkDebug: - debug("%s", szText); + debug("%s", text); break; } } -void ScriptController::PrintMessage(Message::EKind eKind, const char* szFormat, ...) +void ScriptController::PrintMessage(Message::EKind kind, const char* format, ...) { char tmp2[1024]; va_list ap; - va_start(ap, szFormat); - vsnprintf(tmp2, 1024, szFormat, ap); + va_start(ap, format); + vsnprintf(tmp2, 1024, format, ap); tmp2[1024-1] = '\0'; va_end(ap); char tmp3[1024]; - if (m_szLogPrefix) + if (m_logPrefix) { - snprintf(tmp3, 1024, "%s: %s", m_szLogPrefix, tmp2); + snprintf(tmp3, 1024, "%s: %s", m_logPrefix, tmp2); } else { @@ -798,5 +798,5 @@ void ScriptController::PrintMessage(Message::EKind eKind, const char* szFormat, } tmp3[1024-1] = '\0'; - AddMessage(eKind, tmp3); + AddMessage(kind, tmp3); } diff --git a/daemon/util/Script.h b/daemon/util/Script.h index 7939732e..10073d63 100644 --- a/daemon/util/Script.h +++ b/daemon/util/Script.h @@ -43,7 +43,7 @@ public: ~EnvironmentStrings(); void Clear(); void InitFromCurrentProcess(); - void Append(char* szString); + void Append(char* string); #ifdef WIN32 char* GetStrings(); #else @@ -54,36 +54,36 @@ public: class ScriptController { private: - const char* m_szScript; - const char* m_szWorkingDir; - const char** m_szArgs; - bool m_bFreeArgs; - const char* m_szStdArgs[2]; - const char* m_szInfoName; - const char* m_szLogPrefix; + const char* m_script; + const char* m_workingDir; + const char** m_args; + bool m_freeArgs; + const char* m_stdArgs[2]; + const char* m_infoName; + const char* m_logPrefix; EnvironmentStrings m_environmentStrings; - bool m_bTerminated; - bool m_bDetached; - FILE* m_pReadpipe; + bool m_terminated; + bool m_detached; + FILE* m_readpipe; #ifdef WIN32 HANDLE m_hProcess; - char m_szCmdLine[2048]; + char m_cmdLine[2048]; #else pid_t m_hProcess; #endif typedef std::vector RunningScripts; - static RunningScripts m_RunningScripts; - static Mutex m_mutexRunning; + static RunningScripts m_runningScripts; + static Mutex m_runningMutex; protected: - void ProcessOutput(char* szText); - virtual bool ReadLine(char* szBuf, int iBufSize, FILE* pStream); - void PrintMessage(Message::EKind eKind, const char* szFormat, ...); - virtual void AddMessage(Message::EKind eKind, const char* szText); - bool GetTerminated() { return m_bTerminated; } + void ProcessOutput(char* text); + virtual bool ReadLine(char* buf, int bufSize, FILE* stream); + void PrintMessage(Message::EKind kind, const char* format, ...); + virtual void AddMessage(Message::EKind kind, const char* text); + bool GetTerminated() { return m_terminated; } void ResetEnv(); - void PrepareEnvOptions(const char* szStripPrefix); + void PrepareEnvOptions(const char* stripPrefix); void PrepareArgs(); void UnregisterRunningScript(); @@ -96,16 +96,16 @@ public: void Detach(); static void TerminateAll(); - void SetScript(const char* szScript) { m_szScript = szScript; } - const char* GetScript() { return m_szScript; } - void SetWorkingDir(const char* szWorkingDir) { m_szWorkingDir = szWorkingDir; } - void SetArgs(const char** szArgs, bool bFreeArgs) { m_szArgs = szArgs; m_bFreeArgs = bFreeArgs; } - void SetInfoName(const char* szInfoName) { m_szInfoName = szInfoName; } - const char* GetInfoName() { return m_szInfoName; } - void SetLogPrefix(const char* szLogPrefix) { m_szLogPrefix = szLogPrefix; } - void SetEnvVar(const char* szName, const char* szValue); - void SetEnvVarSpecial(const char* szPrefix, const char* szName, const char* szValue); - void SetIntEnvVar(const char* szName, int iValue); + void SetScript(const char* script) { m_script = script; } + const char* GetScript() { return m_script; } + void SetWorkingDir(const char* workingDir) { m_workingDir = workingDir; } + void SetArgs(const char** args, bool freeArgs) { m_args = args; m_freeArgs = freeArgs; } + void SetInfoName(const char* infoName) { m_infoName = infoName; } + const char* GetInfoName() { return m_infoName; } + void SetLogPrefix(const char* logPrefix) { m_logPrefix = logPrefix; } + void SetEnvVar(const char* name, const char* value); + void SetEnvVarSpecial(const char* prefix, const char* name, const char* value); + void SetIntEnvVar(const char* name, int value); }; #endif diff --git a/daemon/util/Service.cpp b/daemon/util/Service.cpp index e3b25644..a83bc34b 100644 --- a/daemon/util/Service.cpp +++ b/daemon/util/Service.cpp @@ -49,7 +49,7 @@ Service::Service() { - m_iLastTick = 0; + m_lastTick = 0; g_pServiceCoordinator->RegisterService(this); } @@ -69,31 +69,31 @@ void ServiceCoordinator::Run() { debug("Entering ServiceCoordinator-loop"); - const int iStepMSec = 100; - int iCurTick = 0; + const int stepMSec = 100; + int curTick = 0; while (!IsStopped()) { - for (ServiceList::iterator it = m_Services.begin(); it != m_Services.end(); it++) + for (ServiceList::iterator it = m_services.begin(); it != m_services.end(); it++) { - Service* pService = *it; - if (iCurTick >= pService->m_iLastTick + pService->ServiceInterval() || // interval expired - iCurTick == 0 || // first start - iCurTick + 10000 < pService->m_iLastTick) // int overflow + Service* service = *it; + if (curTick >= service->m_lastTick + service->ServiceInterval() || // interval expired + curTick == 0 || // first start + curTick + 10000 < service->m_lastTick) // int overflow { - pService->ServiceWork(); - pService->m_iLastTick = iCurTick; + service->ServiceWork(); + service->m_lastTick = curTick; } } - iCurTick += iStepMSec; - usleep(iStepMSec * 1000); + curTick += stepMSec; + usleep(stepMSec * 1000); } debug("Exiting ServiceCoordinator-loop"); } -void ServiceCoordinator::RegisterService(Service* pService) +void ServiceCoordinator::RegisterService(Service* service) { - m_Services.push_back(pService); + m_services.push_back(service); } diff --git a/daemon/util/Service.h b/daemon/util/Service.h index d8a15867..a2d7db12 100644 --- a/daemon/util/Service.h +++ b/daemon/util/Service.h @@ -33,7 +33,7 @@ class Service { private: - int m_iLastTick; + int m_lastTick; protected: virtual int ServiceInterval() = 0; @@ -51,9 +51,9 @@ public: typedef std::vector ServiceList; private: - ServiceList m_Services; + ServiceList m_services; - void RegisterService(Service* pService); + void RegisterService(Service* service); friend class Service; diff --git a/daemon/util/Thread.cpp b/daemon/util/Thread.cpp index f2a8a87e..4d8d9cb7 100644 --- a/daemon/util/Thread.cpp +++ b/daemon/util/Thread.cpp @@ -46,54 +46,54 @@ #include "Log.h" #include "Thread.h" -int Thread::m_iThreadCount = 1; // take the main program thread into account -Mutex* Thread::m_pMutexThread; +int Thread::m_threadCount = 1; // take the main program thread into account +Mutex* Thread::m_mutexThread; Mutex::Mutex() { #ifdef WIN32 - m_pMutexObj = (CRITICAL_SECTION*)malloc(sizeof(CRITICAL_SECTION)); - InitializeCriticalSection((CRITICAL_SECTION*)m_pMutexObj); + m_mutexObj = (CRITICAL_SECTION*)malloc(sizeof(CRITICAL_SECTION)); + InitializeCriticalSection((CRITICAL_SECTION*)m_mutexObj); #else - m_pMutexObj = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)); - pthread_mutex_init((pthread_mutex_t*)m_pMutexObj, NULL); + m_mutexObj = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)); + pthread_mutex_init((pthread_mutex_t*)m_mutexObj, NULL); #endif } Mutex::~ Mutex() { #ifdef WIN32 - DeleteCriticalSection((CRITICAL_SECTION*)m_pMutexObj); + DeleteCriticalSection((CRITICAL_SECTION*)m_mutexObj); #else - pthread_mutex_destroy((pthread_mutex_t*)m_pMutexObj); + pthread_mutex_destroy((pthread_mutex_t*)m_mutexObj); #endif - free(m_pMutexObj); + free(m_mutexObj); } void Mutex::Lock() { #ifdef WIN32 - EnterCriticalSection((CRITICAL_SECTION*)m_pMutexObj); + EnterCriticalSection((CRITICAL_SECTION*)m_mutexObj); #ifdef DEBUG // CriticalSections on Windows can be locked many times from the same thread, // but we do not want this and must treat such situations as errors and detect them. - if (((CRITICAL_SECTION*)m_pMutexObj)->RecursionCount > 1) + if (((CRITICAL_SECTION*)m_mutexObj)->RecursionCount > 1) { error("Internal program error: inconsistent thread-lock detected"); } #endif #else - pthread_mutex_lock((pthread_mutex_t*)m_pMutexObj); + pthread_mutex_lock((pthread_mutex_t*)m_mutexObj); #endif } void Mutex::Unlock() { #ifdef WIN32 - LeaveCriticalSection((CRITICAL_SECTION*)m_pMutexObj); + LeaveCriticalSection((CRITICAL_SECTION*)m_mutexObj); #else - pthread_mutex_unlock((pthread_mutex_t*)m_pMutexObj); + pthread_mutex_unlock((pthread_mutex_t*)m_mutexObj); #endif } @@ -102,14 +102,14 @@ void Thread::Init() { debug("Initializing global thread data"); - m_pMutexThread = new Mutex(); + m_mutexThread = new Mutex(); } void Thread::Final() { debug("Finalizing global thread data"); - delete m_pMutexThread; + delete m_mutexThread; } Thread::Thread() @@ -117,21 +117,21 @@ Thread::Thread() debug("Creating Thread"); #ifdef WIN32 - m_pThreadObj = NULL; + m_threadObj = NULL; #else - m_pThreadObj = (pthread_t*)malloc(sizeof(pthread_t)); - *((pthread_t*)m_pThreadObj) = 0; + m_threadObj = (pthread_t*)malloc(sizeof(pthread_t)); + *((pthread_t*)m_threadObj) = 0; #endif - m_bRunning = false; - m_bStopped = false; - m_bAutoDestroy = false; + m_running = false; + m_stopped = false; + m_autoDestroy = false; } Thread::~Thread() { debug("Destroying Thread"); #ifndef WIN32 - free(m_pThreadObj); + free(m_threadObj); #endif } @@ -139,7 +139,7 @@ void Thread::Start() { debug("Starting Thread"); - m_bRunning = true; + m_running = true; // NOTE: we must guarantee, that in a time we set m_bRunning // to value returned from pthread_create, the thread-object still exists. @@ -149,86 +149,86 @@ void Thread::Start() // We lock mutex m_pMutexThread on calling pthread_create; the started thread // then also try to lock the mutex (see thread_handler) and therefore // must wait until we unlock it - m_pMutexThread->Lock(); + m_mutexThread->Lock(); #ifdef WIN32 - m_pThreadObj = (HANDLE)_beginthread(Thread::thread_handler, 0, (void *)this); - m_bRunning = m_pThreadObj != NULL; + m_threadObj = (HANDLE)_beginthread(Thread::thread_handler, 0, (void *)this); + m_running = m_threadObj != NULL; #else - pthread_attr_t m_Attr; - pthread_attr_init(&m_Attr); - pthread_attr_setdetachstate(&m_Attr, PTHREAD_CREATE_DETACHED); - pthread_attr_setinheritsched(&m_Attr , PTHREAD_INHERIT_SCHED); - m_bRunning = !pthread_create((pthread_t*)m_pThreadObj, &m_Attr, Thread::thread_handler, (void *) this); - pthread_attr_destroy(&m_Attr); + pthread_attr_t m_attr; + pthread_attr_init(&m_attr); + pthread_attr_setdetachstate(&m_attr, PTHREAD_CREATE_DETACHED); + pthread_attr_setinheritsched(&m_attr , PTHREAD_INHERIT_SCHED); + m_running = !pthread_create((pthread_t*)m_threadObj, &m_attr, Thread::thread_handler, (void *) this); + pthread_attr_destroy(&m_attr); #endif - m_pMutexThread->Unlock(); + m_mutexThread->Unlock(); } void Thread::Stop() { debug("Stopping Thread"); - m_bStopped = true; + m_stopped = true; } void Thread::Resume() { debug("Resuming Thread"); - m_bStopped = false; + m_stopped = false; } bool Thread::Kill() { debug("Killing Thread"); - m_pMutexThread->Lock(); + m_mutexThread->Lock(); #ifdef WIN32 - bool terminated = TerminateThread((HANDLE)m_pThreadObj, 0) != 0; + bool terminated = TerminateThread((HANDLE)m_threadObj, 0) != 0; #else - bool terminated = pthread_cancel(*(pthread_t*)m_pThreadObj) == 0; + bool terminated = pthread_cancel(*(pthread_t*)m_threadObj) == 0; #endif if (terminated) { - m_iThreadCount--; + m_threadCount--; } - m_pMutexThread->Unlock(); + m_mutexThread->Unlock(); return terminated; } #ifdef WIN32 -void __cdecl Thread::thread_handler(void* pObject) +void __cdecl Thread::thread_handler(void* object) #else -void* Thread::thread_handler(void* pObject) +void* Thread::thread_handler(void* object) #endif { - m_pMutexThread->Lock(); - m_iThreadCount++; - m_pMutexThread->Unlock(); + m_mutexThread->Lock(); + m_threadCount++; + m_mutexThread->Unlock(); debug("Entering Thread-func"); - Thread* pThread = (Thread*)pObject; + Thread* thread = (Thread*)object; - pThread->Run(); + thread->Run(); debug("Thread-func exited"); - pThread->m_bRunning = false; + thread->m_running = false; - if (pThread->m_bAutoDestroy) + if (thread->m_autoDestroy) { debug("Autodestroying Thread-object"); - delete pThread; + delete thread; } - m_pMutexThread->Lock(); - m_iThreadCount--; - m_pMutexThread->Unlock(); + m_mutexThread->Lock(); + m_threadCount--; + m_mutexThread->Unlock(); #ifndef WIN32 return NULL; @@ -237,8 +237,8 @@ void* Thread::thread_handler(void* pObject) int Thread::GetThreadCount() { - m_pMutexThread->Lock(); - int iThreadCount = m_iThreadCount; - m_pMutexThread->Unlock(); - return iThreadCount; + m_mutexThread->Lock(); + int threadCount = m_threadCount; + m_mutexThread->Unlock(); + return threadCount; } diff --git a/daemon/util/Thread.h b/daemon/util/Thread.h index 6df8c55c..cd06325b 100644 --- a/daemon/util/Thread.h +++ b/daemon/util/Thread.h @@ -30,7 +30,7 @@ class Mutex { private: - void* m_pMutexObj; + void* m_mutexObj; public: Mutex(); @@ -42,17 +42,17 @@ public: class Thread { private: - static Mutex* m_pMutexThread; - static int m_iThreadCount; - void* m_pThreadObj; - bool m_bRunning; - bool m_bStopped; - bool m_bAutoDestroy; + static Mutex* m_mutexThread; + static int m_threadCount; + void* m_threadObj; + bool m_running; + bool m_stopped; + bool m_autoDestroy; #ifdef WIN32 - static void __cdecl thread_handler(void* pObject); + static void __cdecl thread_handler(void* object); #else - static void *thread_handler(void* pObject); + static void *thread_handler(void* object); #endif public: @@ -66,11 +66,11 @@ public: virtual void Resume(); bool Kill(); - bool IsStopped() { return m_bStopped; }; - bool IsRunning() const { return m_bRunning; } - void SetRunning(bool bOnOff) { m_bRunning = bOnOff; } - bool GetAutoDestroy() { return m_bAutoDestroy; } - void SetAutoDestroy(bool bAutoDestroy) { m_bAutoDestroy = bAutoDestroy; } + bool IsStopped() { return m_stopped; }; + bool IsRunning() const { return m_running; } + void SetRunning(bool onOff) { m_running = onOff; } + bool GetAutoDestroy() { return m_autoDestroy; } + void SetAutoDestroy(bool autoDestroy) { m_autoDestroy = autoDestroy; } static int GetThreadCount(); protected: diff --git a/daemon/util/Util.cpp b/daemon/util/Util.cpp index f7c4378e..106ed83d 100644 --- a/daemon/util/Util.cpp +++ b/daemon/util/Util.cpp @@ -144,13 +144,13 @@ int getopt(int argc, char *argv[], char *optstring) return c; } -DirBrowser::DirBrowser(const char* szPath) +DirBrowser::DirBrowser(const char* path) { - char szMask[MAX_PATH + 1]; - snprintf(szMask, MAX_PATH + 1, "%s%c*.*", szPath, (int)PATH_SEPARATOR); - szMask[MAX_PATH] = '\0'; - m_hFile = FindFirstFile(szMask, &m_FindData); - m_bFirst = true; + char mask[MAX_PATH + 1]; + snprintf(mask, MAX_PATH + 1, "%s%c*.*", path, (int)PATH_SEPARATOR); + mask[MAX_PATH] = '\0'; + m_hFile = FindFirstFile(mask, &m_findData); + m_first = true; } DirBrowser::~DirBrowser() @@ -163,19 +163,19 @@ DirBrowser::~DirBrowser() const char* DirBrowser::Next() { - bool bOK = false; - if (m_bFirst) + bool ok = false; + if (m_first) { - bOK = m_hFile != INVALID_HANDLE_VALUE; - m_bFirst = false; + ok = m_hFile != INVALID_HANDLE_VALUE; + m_first = false; } else { - bOK = FindNextFile(m_hFile, &m_FindData) != 0; + ok = FindNextFile(m_hFile, &m_findData) != 0; } - if (bOK) + if (ok) { - return m_FindData.cFileName; + return m_findData.cFileName; } return NULL; } @@ -183,35 +183,35 @@ const char* DirBrowser::Next() #else #ifdef DIRBROWSER_SNAPSHOT -DirBrowser::DirBrowser(const char* szPath, bool bSnapshot) +DirBrowser::DirBrowser(const char* path, bool snapshot) #else -DirBrowser::DirBrowser(const char* szPath) +DirBrowser::DirBrowser(const char* path) #endif { #ifdef DIRBROWSER_SNAPSHOT - m_bSnapshot = bSnapshot; - if (m_bSnapshot) + m_snapshot = snapshot; + if (m_snapshot) { - DirBrowser dir(szPath, false); + DirBrowser dir(path, false); while (const char* filename = dir.Next()) { - m_Snapshot.push_back(strdup(filename)); + m_snapshot.push_back(strdup(filename)); } - m_itSnapshot = m_Snapshot.begin(); + m_itSnapshot = m_snapshot.begin(); } else #endif { - m_pDir = opendir(szPath); + m_dir = opendir(path); } } DirBrowser::~DirBrowser() { #ifdef DIRBROWSER_SNAPSHOT - if (m_bSnapshot) + if (m_snapshot) { - for (FileList::iterator it = m_Snapshot.begin(); it != m_Snapshot.end(); it++) + for (FileList::iterator it = m_snapshot.begin(); it != m_snapshot.end(); it++) { delete *it; } @@ -219,9 +219,9 @@ DirBrowser::~DirBrowser() else #endif { - if (m_pDir) + if (m_dir) { - closedir((DIR*)m_pDir); + closedir((DIR*)m_dir); } } } @@ -229,19 +229,19 @@ DirBrowser::~DirBrowser() const char* DirBrowser::Next() { #ifdef DIRBROWSER_SNAPSHOT - if (m_bSnapshot) + if (m_snapshot) { - return m_itSnapshot == m_Snapshot.end() ? NULL : *m_itSnapshot++; + return m_itSnapshot == m_snapshot.end() ? NULL : *m_itSnapshot++; } else #endif { - if (m_pDir) + if (m_dir) { - m_pFindData = readdir((DIR*)m_pDir); - if (m_pFindData) + m_findData = readdir((DIR*)m_dir); + if (m_findData) { - return m_pFindData->d_name; + return m_findData->d_name; } } return NULL; @@ -253,75 +253,75 @@ const char* DirBrowser::Next() StringBuilder::StringBuilder() { - m_szBuffer = NULL; - m_iBufferSize = 0; - m_iUsedSize = 0; - m_iGrowSize = 10240; + m_buffer = NULL; + m_bufferSize = 0; + m_usedSize = 0; + m_growSize = 10240; } StringBuilder::~StringBuilder() { - free(m_szBuffer); + free(m_buffer); } void StringBuilder::Clear() { - free(m_szBuffer); - m_szBuffer = NULL; - m_iBufferSize = 0; - m_iUsedSize = 0; + free(m_buffer); + m_buffer = NULL; + m_bufferSize = 0; + m_usedSize = 0; } -void StringBuilder::Append(const char* szStr) +void StringBuilder::Append(const char* str) { - int iPartLen = strlen(szStr); - Reserve(iPartLen + 1); - strcpy(m_szBuffer + m_iUsedSize, szStr); - m_iUsedSize += iPartLen; - m_szBuffer[m_iUsedSize] = '\0'; + int partLen = strlen(str); + Reserve(partLen + 1); + strcpy(m_buffer + m_usedSize, str); + m_usedSize += partLen; + m_buffer[m_usedSize] = '\0'; } -void StringBuilder::AppendFmt(const char* szFormat, ...) +void StringBuilder::AppendFmt(const char* format, ...) { va_list args; - va_start(args, szFormat); - AppendFmtV(szFormat, args); + va_start(args, format); + AppendFmtV(format, args); va_end(args); } -void StringBuilder::AppendFmtV(const char* szFormat, va_list ap) +void StringBuilder::AppendFmtV(const char* format, va_list ap) { va_list ap2; va_copy(ap2, ap); - int iRemainingSize = m_iBufferSize - m_iUsedSize; - int m = vsnprintf(m_szBuffer + m_iUsedSize, iRemainingSize, szFormat, ap); + int remainingSize = m_bufferSize - m_usedSize; + int m = vsnprintf(m_buffer + m_usedSize, remainingSize, format, ap); #ifdef WIN32 if (m == -1) { - m = _vscprintf(szFormat, ap); + m = _vscprintf(format, ap); } #endif - if (m + 1 > iRemainingSize) + if (m + 1 > remainingSize) { - Reserve(m - iRemainingSize + m_iGrowSize); - iRemainingSize = m_iBufferSize - m_iUsedSize; - m = vsnprintf(m_szBuffer + m_iUsedSize, iRemainingSize, szFormat, ap2); + Reserve(m - remainingSize + m_growSize); + remainingSize = m_bufferSize - m_usedSize; + m = vsnprintf(m_buffer + m_usedSize, remainingSize, format, ap2); } if (m >= 0) { - m_szBuffer[m_iUsedSize += m] = '\0'; + m_buffer[m_usedSize += m] = '\0'; } va_end(ap2); } -void StringBuilder::Reserve(int iSize) +void StringBuilder::Reserve(int size) { - if (m_iUsedSize + iSize > m_iBufferSize) + if (m_usedSize + size > m_bufferSize) { - m_iBufferSize += iSize + m_iGrowSize; - m_szBuffer = (char*)realloc(m_szBuffer, m_iBufferSize); + m_bufferSize += size + m_growSize; + m_buffer = (char*)realloc(m_buffer, m_bufferSize); } } @@ -349,9 +349,9 @@ char* Util::BaseFileName(const char* filename) } } -void Util::NormalizePathSeparators(char* szPath) +void Util::NormalizePathSeparators(char* path) { - for (char* p = szPath; *p; p++) + for (char* p = path; *p; p++) { if (*p == ALT_PATH_SEPARATOR) { @@ -360,86 +360,86 @@ void Util::NormalizePathSeparators(char* szPath) } } -bool Util::ForceDirectories(const char* szPath, char* szErrBuf, int iBufSize) +bool Util::ForceDirectories(const char* path, char* errBuf, int bufSize) { - *szErrBuf = '\0'; - char szSysErrStr[256]; - char szNormPath[1024]; - strncpy(szNormPath, szPath, 1024); - szNormPath[1024-1] = '\0'; - NormalizePathSeparators(szNormPath); - int iLen = strlen(szNormPath); - if ((iLen > 0) && szNormPath[iLen-1] == PATH_SEPARATOR + *errBuf = '\0'; + char sysErrStr[256]; + char normPath[1024]; + strncpy(normPath, path, 1024); + normPath[1024-1] = '\0'; + NormalizePathSeparators(normPath); + int len = strlen(normPath); + if ((len > 0) && normPath[len-1] == PATH_SEPARATOR #ifdef WIN32 - && iLen > 3 + && len > 3 #endif ) { - szNormPath[iLen-1] = '\0'; + normPath[len-1] = '\0'; } struct stat buffer; - bool bOK = !stat(szNormPath, &buffer); - if (!bOK && errno != ENOENT) + bool ok = !stat(normPath, &buffer); + if (!ok && errno != ENOENT) { - snprintf(szErrBuf, iBufSize, "could not read information for directory %s: errno %i, %s", szNormPath, errno, GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); - szErrBuf[iBufSize-1] = 0; + snprintf(errBuf, bufSize, "could not read information for directory %s: errno %i, %s", normPath, errno, GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); + errBuf[bufSize-1] = 0; return false; } - if (bOK && !S_ISDIR(buffer.st_mode)) + if (ok && !S_ISDIR(buffer.st_mode)) { - snprintf(szErrBuf, iBufSize, "path %s is not a directory", szNormPath); - szErrBuf[iBufSize-1] = 0; + snprintf(errBuf, bufSize, "path %s is not a directory", normPath); + errBuf[bufSize-1] = 0; return false; } - if (!bOK + if (!ok #ifdef WIN32 - && strlen(szNormPath) > 2 + && strlen(normPath) > 2 #endif ) { - char szParentPath[1024]; - strncpy(szParentPath, szNormPath, 1024); - szParentPath[1024-1] = '\0'; - char* p = (char*)strrchr(szParentPath, PATH_SEPARATOR); + char parentPath[1024]; + strncpy(parentPath, normPath, 1024); + parentPath[1024-1] = '\0'; + char* p = (char*)strrchr(parentPath, PATH_SEPARATOR); if (p) { #ifdef WIN32 - if (p - szParentPath == 2 && szParentPath[1] == ':' && strlen(szParentPath) > 2) + if (p - parentPath == 2 && parentPath[1] == ':' && strlen(parentPath) > 2) { - szParentPath[3] = '\0'; + parentPath[3] = '\0'; } else #endif { *p = '\0'; } - if (strlen(szParentPath) != strlen(szPath) && !ForceDirectories(szParentPath, szErrBuf, iBufSize)) + if (strlen(parentPath) != strlen(path) && !ForceDirectories(parentPath, errBuf, bufSize)) { return false; } } - if (mkdir(szNormPath, S_DIRMODE) != 0 && errno != EEXIST) + if (mkdir(normPath, S_DIRMODE) != 0 && errno != EEXIST) { - snprintf(szErrBuf, iBufSize, "could not create directory %s: %s", szNormPath, GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); - szErrBuf[iBufSize-1] = 0; + snprintf(errBuf, bufSize, "could not create directory %s: %s", normPath, GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); + errBuf[bufSize-1] = 0; return false; } - if (stat(szNormPath, &buffer) != 0) + if (stat(normPath, &buffer) != 0) { - snprintf(szErrBuf, iBufSize, "could not read information for directory %s: %s", szNormPath, GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); - szErrBuf[iBufSize-1] = 0; + snprintf(errBuf, bufSize, "could not read information for directory %s: %s", normPath, GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); + errBuf[bufSize-1] = 0; return false; } if (!S_ISDIR(buffer.st_mode)) { - snprintf(szErrBuf, iBufSize, "path %s is not a directory", szNormPath); - szErrBuf[iBufSize-1] = 0; + snprintf(errBuf, bufSize, "path %s is not a directory", normPath); + errBuf[bufSize-1] = 0; return false; } } @@ -447,27 +447,27 @@ bool Util::ForceDirectories(const char* szPath, char* szErrBuf, int iBufSize) return true; } -bool Util::GetCurrentDirectory(char* szBuffer, int iBufSize) +bool Util::GetCurrentDirectory(char* buffer, int bufSize) { #ifdef WIN32 - return ::GetCurrentDirectory(iBufSize, szBuffer) != NULL; + return ::GetCurrentDirectory(bufSize, buffer) != NULL; #else - return getcwd(szBuffer, iBufSize) != NULL; + return getcwd(buffer, bufSize) != NULL; #endif } -bool Util::SetCurrentDirectory(const char* szDirFilename) +bool Util::SetCurrentDirectory(const char* dirFilename) { #ifdef WIN32 - return ::SetCurrentDirectory(szDirFilename); + return ::SetCurrentDirectory(dirFilename); #else - return chdir(szDirFilename) == 0; + return chdir(dirFilename) == 0; #endif } -bool Util::DirEmpty(const char* szDirFilename) +bool Util::DirEmpty(const char* dirFilename) { - DirBrowser dir(szDirFilename); + DirBrowser dir(dirFilename); while (const char* filename = dir.Next()) { if (strcmp(filename, ".") && strcmp(filename, "..")) @@ -478,61 +478,61 @@ bool Util::DirEmpty(const char* szDirFilename) return true; } -bool Util::LoadFileIntoBuffer(const char* szFileName, char** pBuffer, int* pBufferLength) +bool Util::LoadFileIntoBuffer(const char* fileName, char** buffer, int* bufferLength) { - FILE* pFile = fopen(szFileName, FOPEN_RB); - if (!pFile) + FILE* file = fopen(fileName, FOPEN_RB); + if (!file) { return false; } // obtain file size. - fseek(pFile , 0 , SEEK_END); - int iSize = (int)ftell(pFile); - rewind(pFile); + fseek(file , 0 , SEEK_END); + int size = (int)ftell(file); + rewind(file); // allocate memory to contain the whole file. - *pBuffer = (char*) malloc(iSize + 1); - if (!*pBuffer) + *buffer = (char*) malloc(size + 1); + if (!*buffer) { return false; } // copy the file into the buffer. - fread(*pBuffer, 1, iSize, pFile); + fread(*buffer, 1, size, file); - fclose(pFile); + fclose(file); - (*pBuffer)[iSize] = 0; + (*buffer)[size] = 0; - *pBufferLength = iSize + 1; + *bufferLength = size + 1; return true; } -bool Util::SaveBufferIntoFile(const char* szFileName, const char* szBuffer, int iBufLen) +bool Util::SaveBufferIntoFile(const char* fileName, const char* buffer, int bufLen) { - FILE* pFile = fopen(szFileName, FOPEN_WB); - if (!pFile) + FILE* file = fopen(fileName, FOPEN_WB); + if (!file) { return false; } - int iWrittenBytes = fwrite(szBuffer, 1, iBufLen, pFile); - fclose(pFile); + int writtenBytes = fwrite(buffer, 1, bufLen, file); + fclose(file); - return iWrittenBytes == iBufLen; + return writtenBytes == bufLen; } -bool Util::CreateSparseFile(const char* szFilename, long long iSize, char* szErrBuf, int iBufSize) +bool Util::CreateSparseFile(const char* filename, long long size, char* errBuf, int bufSize) { - *szErrBuf = '\0'; - bool bOK = false; + *errBuf = '\0'; + bool ok = false; #ifdef WIN32 - HANDLE hFile = CreateFile(szFilename, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_NEW, 0, NULL); + HANDLE hFile = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_NEW, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { - GetLastErrorMessage(szErrBuf, sizeof(iBufSize)); + GetLastErrorMessage(errBuf, sizeof(bufSize)); return false; } // first try to create sparse file (supported only on NTFS partitions), @@ -540,73 +540,73 @@ bool Util::CreateSparseFile(const char* szFilename, long long iSize, char* szErr DWORD dwBytesReturned; DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &dwBytesReturned, NULL); - LARGE_INTEGER iSize64; - iSize64.QuadPart = iSize; - SetFilePointerEx(hFile, iSize64, NULL, FILE_END); + LARGE_INTEGER size64; + size64.QuadPart = size; + SetFilePointerEx(hFile, size64, NULL, FILE_END); SetEndOfFile(hFile); CloseHandle(hFile); - bOK = true; + ok = true; #else // create file - FILE* pFile = fopen(szFilename, FOPEN_AB); - if (!pFile) + FILE* file = fopen(filename, FOPEN_AB); + if (!file) { - GetLastErrorMessage(szErrBuf, sizeof(iBufSize)); + GetLastErrorMessage(errBuf, sizeof(bufSize)); return false; } - fclose(pFile); + fclose(file); // there are no reliable function to expand file on POSIX, so we must try different approaches, // starting with the fastest one and hoping it will work // 1) set file size using function "truncate" (this is fast, if it works) - truncate(szFilename, iSize); + truncate(filename, size); // check if it worked - bOK = FileSize(szFilename) == iSize; - if (!bOK) + ok = FileSize(filename) == size; + if (!ok) { // 2) truncate did not work, expanding the file by writing to it (that's slow) - truncate(szFilename, 0); - pFile = fopen(szFilename, FOPEN_AB); - if (!pFile) + truncate(filename, 0); + file = fopen(filename, FOPEN_AB); + if (!file) { - GetLastErrorMessage(szErrBuf, sizeof(iBufSize)); + GetLastErrorMessage(errBuf, sizeof(bufSize)); return false; } char c = '0'; - fwrite(&c, 1, iSize, pFile); - fclose(pFile); - bOK = FileSize(szFilename) == iSize; + fwrite(&c, 1, size, file); + fclose(file); + ok = FileSize(filename) == size; } #endif - return bOK; + return ok; } -bool Util::TruncateFile(const char* szFilename, int iSize) +bool Util::TruncateFile(const char* filename, int size) { - bool bOK = false; + bool ok = false; #ifdef WIN32 - FILE *file = fopen(szFilename, FOPEN_RBP); - fseek(file, iSize, SEEK_SET); - bOK = SetEndOfFile((HANDLE)_get_osfhandle(_fileno(file))) != 0; + FILE *file = fopen(filename, FOPEN_RBP); + fseek(file, size, SEEK_SET); + ok = SetEndOfFile((HANDLE)_get_osfhandle(_fileno(file))) != 0; fclose(file); #else - bOK = truncate(szFilename, iSize) == 0; + ok = truncate(filename, size) == 0; #endif - return bOK; + return ok; } //replace bad chars in filename -void Util::MakeValidFilename(char* szFilename, char cReplaceChar, bool bAllowSlashes) +void Util::MakeValidFilename(char* filename, char cReplaceChar, bool allowSlashes) { - const char* szReplaceChars = bAllowSlashes ? ":*?\"><\n\r\t" : "\\/:*?\"><\n\r\t"; - char* p = szFilename; + const char* replaceChars = allowSlashes ? ":*?\"><\n\r\t" : "\\/:*?\"><\n\r\t"; + char* p = filename; while (*p) { - if (strchr(szReplaceChars, *p)) + if (strchr(replaceChars, *p)) { *p = cReplaceChar; } - if (bAllowSlashes && *p == ALT_PATH_SEPARATOR) + if (allowSlashes && *p == ALT_PATH_SEPARATOR) { *p = PATH_SEPARATOR; } @@ -615,52 +615,52 @@ void Util::MakeValidFilename(char* szFilename, char cReplaceChar, bool bAllowSla // remove trailing dots and spaces. they are not allowed in directory names on windows, // but we remove them on posix also, in a case the directory is accessed from windows via samba. - for (int iLen = strlen(szFilename); iLen > 0 && (szFilename[iLen - 1] == '.' || szFilename[iLen - 1] == ' '); iLen--) + for (int len = strlen(filename); len > 0 && (filename[len - 1] == '.' || filename[len - 1] == ' '); len--) { - szFilename[iLen - 1] = '\0'; + filename[len - 1] = '\0'; } } // returns TRUE if the name was changed by adding duplicate-suffix -bool Util::MakeUniqueFilename(char* szDestBufFilename, int iDestBufSize, const char* szDestDir, const char* szBasename) +bool Util::MakeUniqueFilename(char* destBufFilename, int destBufSize, const char* destDir, const char* basename) { - snprintf(szDestBufFilename, iDestBufSize, "%s%c%s", szDestDir, (int)PATH_SEPARATOR, szBasename); - szDestBufFilename[iDestBufSize-1] = '\0'; + snprintf(destBufFilename, destBufSize, "%s%c%s", destDir, (int)PATH_SEPARATOR, basename); + destBufFilename[destBufSize-1] = '\0'; - int iDupeNumber = 0; - while (FileExists(szDestBufFilename)) + int dupeNumber = 0; + while (FileExists(destBufFilename)) { - iDupeNumber++; + dupeNumber++; - const char* szExtension = strrchr(szBasename, '.'); - if (szExtension && szExtension != szBasename) + const char* extension = strrchr(basename, '.'); + if (extension && extension != basename) { - char szFilenameWithoutExt[1024]; - strncpy(szFilenameWithoutExt, szBasename, 1024); - int iEnd = szExtension - szBasename; - szFilenameWithoutExt[iEnd < 1024 ? iEnd : 1024-1] = '\0'; + char filenameWithoutExt[1024]; + strncpy(filenameWithoutExt, basename, 1024); + int end = extension - basename; + filenameWithoutExt[end < 1024 ? end : 1024-1] = '\0'; - if (!strcasecmp(szExtension, ".par2")) + if (!strcasecmp(extension, ".par2")) { - char* szVolExtension = strrchr(szFilenameWithoutExt, '.'); - if (szVolExtension && szVolExtension != szFilenameWithoutExt && !strncasecmp(szVolExtension, ".vol", 4)) + char* volExtension = strrchr(filenameWithoutExt, '.'); + if (volExtension && volExtension != filenameWithoutExt && !strncasecmp(volExtension, ".vol", 4)) { - *szVolExtension = '\0'; - szExtension = szBasename + (szVolExtension - szFilenameWithoutExt); + *volExtension = '\0'; + extension = basename + (volExtension - filenameWithoutExt); } } - snprintf(szDestBufFilename, iDestBufSize, "%s%c%s.duplicate%d%s", szDestDir, (int)PATH_SEPARATOR, szFilenameWithoutExt, iDupeNumber, szExtension); + snprintf(destBufFilename, destBufSize, "%s%c%s.duplicate%d%s", destDir, (int)PATH_SEPARATOR, filenameWithoutExt, dupeNumber, extension); } else { - snprintf(szDestBufFilename, iDestBufSize, "%s%c%s.duplicate%d", szDestDir, (int)PATH_SEPARATOR, szBasename, iDupeNumber); + snprintf(destBufFilename, destBufSize, "%s%c%s.duplicate%d", destDir, (int)PATH_SEPARATOR, basename, dupeNumber); } - szDestBufFilename[iDestBufSize-1] = '\0'; + destBufFilename[destBufSize-1] = '\0'; } - return iDupeNumber > 0; + return dupeNumber > 0; } long long Util::JoinInt64(unsigned long Hi, unsigned long Lo) @@ -696,46 +696,46 @@ const static char BASE64_DEALPHABET [128] = 49, 50, 51, 0, 0, 0, 0, 0 // 120 - 127 }; -unsigned int DecodeByteQuartet(char* szInputBuffer, char* szOutputBuffer) +unsigned int DecodeByteQuartet(char* inputBuffer, char* outputBuffer) { unsigned int buffer = 0; - if (szInputBuffer[3] == '=') + if (inputBuffer[3] == '=') { - if (szInputBuffer[2] == '=') + if (inputBuffer[2] == '=') { - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[0]]) << 6; - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[1]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[0]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[1]]) << 6; buffer = buffer << 14; - szOutputBuffer [0] = (char)(buffer >> 24); + outputBuffer [0] = (char)(buffer >> 24); return 1; } else { - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[0]]) << 6; - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[1]]) << 6; - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[2]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[0]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[1]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[2]]) << 6; buffer = buffer << 8; - szOutputBuffer [0] = (char)(buffer >> 24); - szOutputBuffer [1] = (char)(buffer >> 16); + outputBuffer [0] = (char)(buffer >> 24); + outputBuffer [1] = (char)(buffer >> 16); return 2; } } else { - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[0]]) << 6; - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[1]]) << 6; - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[2]]) << 6; - buffer = (buffer | BASE64_DEALPHABET [(int)szInputBuffer[3]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[0]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[1]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[2]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[3]]) << 6; buffer = buffer << 2; - szOutputBuffer [0] = (char)(buffer >> 24); - szOutputBuffer [1] = (char)(buffer >> 16); - szOutputBuffer [2] = (char)(buffer >> 8); + outputBuffer [0] = (char)(buffer >> 24); + outputBuffer [1] = (char)(buffer >> 16); + outputBuffer [2] = (char)(buffer >> 8); return 3; } @@ -743,29 +743,29 @@ unsigned int DecodeByteQuartet(char* szInputBuffer, char* szOutputBuffer) return 0; } -bool Util::MoveFile(const char* szSrcFilename, const char* szDstFilename) +bool Util::MoveFile(const char* srcFilename, const char* dstFilename) { - bool bOK = rename(szSrcFilename, szDstFilename) == 0; + bool ok = rename(srcFilename, dstFilename) == 0; #ifndef WIN32 - if (!bOK && errno == EXDEV) + if (!ok && errno == EXDEV) { - bOK = CopyFile(szSrcFilename, szDstFilename) && remove(szSrcFilename) == 0; + ok = CopyFile(srcFilename, dstFilename) && remove(srcFilename) == 0; } #endif - return bOK; + return ok; } -bool Util::CopyFile(const char* szSrcFilename, const char* szDstFilename) +bool Util::CopyFile(const char* srcFilename, const char* dstFilename) { - FILE* infile = fopen(szSrcFilename, FOPEN_RB); + FILE* infile = fopen(srcFilename, FOPEN_RB); if (!infile) { return false; } - FILE* outfile = fopen(szDstFilename, FOPEN_WBP); + FILE* outfile = fopen(dstFilename, FOPEN_WBP); if (!outfile) { fclose(infile); @@ -789,135 +789,135 @@ bool Util::CopyFile(const char* szSrcFilename, const char* szDstFilename) return true; } -bool Util::FileExists(const char* szFilename) +bool Util::FileExists(const char* filename) { #ifdef WIN32 // we use a native windows call because c-lib function "stat" fails on windows if file date is invalid WIN32_FIND_DATA findData; - HANDLE handle = FindFirstFile(szFilename, &findData); + HANDLE handle = FindFirstFile(filename, &findData); if (handle != INVALID_HANDLE_VALUE) { - bool bExists = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0; + bool exists = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0; FindClose(handle); - return bExists; + return exists; } return false; #else struct stat buffer; - bool bExists = !stat(szFilename, &buffer) && S_ISREG(buffer.st_mode); - return bExists; + bool exists = !stat(filename, &buffer) && S_ISREG(buffer.st_mode); + return exists; #endif } -bool Util::FileExists(const char* szPath, const char* szFilenameWithoutPath) +bool Util::FileExists(const char* path, const char* filenameWithoutPath) { char fullFilename[1024]; - snprintf(fullFilename, 1024, "%s%c%s", szPath, (int)PATH_SEPARATOR, szFilenameWithoutPath); + snprintf(fullFilename, 1024, "%s%c%s", path, (int)PATH_SEPARATOR, filenameWithoutPath); fullFilename[1024-1] = '\0'; - bool bExists = Util::FileExists(fullFilename); - return bExists; + bool exists = Util::FileExists(fullFilename); + return exists; } -bool Util::DirectoryExists(const char* szDirFilename) +bool Util::DirectoryExists(const char* dirFilename) { #ifdef WIN32 // we use a native windows call because c-lib function "stat" fails on windows if file date is invalid WIN32_FIND_DATA findData; - HANDLE handle = FindFirstFile(szDirFilename, &findData); + HANDLE handle = FindFirstFile(dirFilename, &findData); if (handle != INVALID_HANDLE_VALUE) { - bool bExists = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; + bool exists = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; FindClose(handle); - return bExists; + return exists; } return false; #else struct stat buffer; - bool bExists = !stat(szDirFilename, &buffer) && S_ISDIR(buffer.st_mode); - return bExists; + bool exists = !stat(dirFilename, &buffer) && S_ISDIR(buffer.st_mode); + return exists; #endif } -bool Util::CreateDirectory(const char* szDirFilename) +bool Util::CreateDirectory(const char* dirFilename) { - mkdir(szDirFilename, S_DIRMODE); - return DirectoryExists(szDirFilename); + mkdir(dirFilename, S_DIRMODE); + return DirectoryExists(dirFilename); } -bool Util::RemoveDirectory(const char* szDirFilename) +bool Util::RemoveDirectory(const char* dirFilename) { #ifdef WIN32 - return _rmdir(szDirFilename) == 0; + return _rmdir(dirFilename) == 0; #else - return remove(szDirFilename) == 0; + return remove(dirFilename) == 0; #endif } -bool Util::DeleteDirectoryWithContent(const char* szDirFilename, char* szErrBuf, int iBufSize) +bool Util::DeleteDirectoryWithContent(const char* dirFilename, char* errBuf, int bufSize) { - *szErrBuf = '\0'; - char szSysErrStr[256]; + *errBuf = '\0'; + char sysErrStr[256]; - bool bDel = false; - bool bOK = true; + bool del = false; + bool ok = true; - DirBrowser dir(szDirFilename); + DirBrowser dir(dirFilename); while (const char* filename = dir.Next()) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", szDirFilename, PATH_SEPARATOR, filename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", dirFilename, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; if (strcmp(filename, ".") && strcmp(filename, "..")) { - if (Util::DirectoryExists(szFullFilename)) + if (Util::DirectoryExists(fullFilename)) { - bDel = DeleteDirectoryWithContent(szFullFilename, szSysErrStr, sizeof(szSysErrStr)); + del = DeleteDirectoryWithContent(fullFilename, sysErrStr, sizeof(sysErrStr)); } else { - bDel = remove(szFullFilename) == 0; + del = remove(fullFilename) == 0; } - bOK &= bDel; - if (!bDel && !*szErrBuf) + ok &= del; + if (!del && !*errBuf) { - snprintf(szErrBuf, iBufSize, "could not delete %s: %s", szFullFilename, GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr))); + snprintf(errBuf, bufSize, "could not delete %s: %s", fullFilename, GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); } } } - bDel = RemoveDirectory(szDirFilename); - bOK &= bDel; - if (!bDel && !*szErrBuf) + del = RemoveDirectory(dirFilename); + ok &= del; + if (!del && !*errBuf) { - GetLastErrorMessage(szErrBuf, iBufSize); + GetLastErrorMessage(errBuf, bufSize); } - return bOK; + return ok; } -long long Util::FileSize(const char* szFilename) +long long Util::FileSize(const char* filename) { #ifdef WIN32 struct _stat32i64 buffer; - _stat32i64(szFilename, &buffer); + _stat32i64(filename, &buffer); #else struct stat buffer; - stat(szFilename, &buffer); + stat(filename, &buffer); #endif return buffer.st_size; } -long long Util::FreeDiskSize(const char* szPath) +long long Util::FreeDiskSize(const char* path) { #ifdef WIN32 - ULARGE_INTEGER lFree, lDummy; - if (GetDiskFreeSpaceEx(szPath, &lFree, &lDummy, &lDummy)) + ULARGE_INTEGER free, dummy; + if (GetDiskFreeSpaceEx(path, &free, &dummy, &dummy)) { - return lFree.QuadPart; + return free.QuadPart; } #else struct statvfs diskdata; - if (!statvfs(szPath, &diskdata)) + if (!statvfs(path, &diskdata)) { return (long long)diskdata.f_frsize * (long long)diskdata.f_bavail; } @@ -925,46 +925,46 @@ long long Util::FreeDiskSize(const char* szPath) return -1; } -bool Util::RenameBak(const char* szFilename, const char* szBakPart, bool bRemoveOldExtension, char* szNewNameBuf, int iNewNameBufSize) +bool Util::RenameBak(const char* filename, const char* bakPart, bool removeOldExtension, char* newNameBuf, int newNameBufSize) { - char szChangedFilename[1024]; + char changedFilename[1024]; - if (bRemoveOldExtension) + if (removeOldExtension) { - strncpy(szChangedFilename, szFilename, 1024); - szChangedFilename[1024-1] = '\0'; - char* szExtension = strrchr(szChangedFilename, '.'); - if (szExtension) + strncpy(changedFilename, filename, 1024); + changedFilename[1024-1] = '\0'; + char* extension = strrchr(changedFilename, '.'); + if (extension) { - *szExtension = '\0'; + *extension = '\0'; } } char bakname[1024]; - snprintf(bakname, 1024, "%s.%s", bRemoveOldExtension ? szChangedFilename : szFilename, szBakPart); + snprintf(bakname, 1024, "%s.%s", removeOldExtension ? changedFilename : filename, bakPart); bakname[1024-1] = '\0'; int i = 2; struct stat buffer; while (!stat(bakname, &buffer)) { - snprintf(bakname, 1024, "%s.%i.%s", bRemoveOldExtension ? szChangedFilename : szFilename, i++, szBakPart); + snprintf(bakname, 1024, "%s.%i.%s", removeOldExtension ? changedFilename : filename, i++, bakPart); bakname[1024-1] = '\0'; } - if (szNewNameBuf) + if (newNameBuf) { - strncpy(szNewNameBuf, bakname, iNewNameBufSize); + strncpy(newNameBuf, bakname, newNameBufSize); } - bool bOK = !rename(szFilename, bakname); - return bOK; + bool ok = !rename(filename, bakname); + return ok; } #ifndef WIN32 -bool Util::ExpandHomePath(const char* szFilename, char* szBuffer, int iBufSize) +bool Util::ExpandHomePath(const char* filename, char* buffer, int bufSize) { - if (szFilename && (szFilename[0] == '~') && (szFilename[1] == '/')) + if (filename && (filename[0] == '~') && (filename[1] == '/')) { // expand home-dir @@ -985,146 +985,146 @@ bool Util::ExpandHomePath(const char* szFilename, char* szBuffer, int iBufSize) if (home[strlen(home)-1] == '/') { - snprintf(szBuffer, iBufSize, "%s%s", home, szFilename + 2); + snprintf(buffer, bufSize, "%s%s", home, filename + 2); } else { - snprintf(szBuffer, iBufSize, "%s/%s", home, szFilename + 2); + snprintf(buffer, bufSize, "%s/%s", home, filename + 2); } - szBuffer[iBufSize - 1] = '\0'; + buffer[bufSize - 1] = '\0'; } else { - strncpy(szBuffer, szFilename ? szFilename : "", iBufSize); - szBuffer[iBufSize - 1] = '\0'; + strncpy(buffer, filename ? filename : "", bufSize); + buffer[bufSize - 1] = '\0'; } return true; } #endif -void Util::ExpandFileName(const char* szFilename, char* szBuffer, int iBufSize) +void Util::ExpandFileName(const char* filename, char* buffer, int bufSize) { #ifdef WIN32 - _fullpath(szBuffer, szFilename, iBufSize); + _fullpath(buffer, filename, bufSize); #else - if (szFilename[0] != '\0' && szFilename[0] != '/') + if (filename[0] != '\0' && filename[0] != '/') { - char szCurDir[MAX_PATH + 1]; - getcwd(szCurDir, sizeof(szCurDir) - 1); // 1 char reserved for adding backslash - int iOffset = 0; - if (szFilename[0] == '.' && szFilename[1] == '/') + char curDir[MAX_PATH + 1]; + getcwd(curDir, sizeof(curDir) - 1); // 1 char reserved for adding backslash + int offset = 0; + if (filename[0] == '.' && filename[1] == '/') { - iOffset += 2; + offset += 2; } - snprintf(szBuffer, iBufSize, "%s/%s", szCurDir, szFilename + iOffset); + snprintf(buffer, bufSize, "%s/%s", curDir, filename + offset); } else { - strncpy(szBuffer, szFilename, iBufSize); - szBuffer[iBufSize - 1] = '\0'; + strncpy(buffer, filename, bufSize); + buffer[bufSize - 1] = '\0'; } #endif } -void Util::GetExeFileName(const char* argv0, char* szBuffer, int iBufSize) +void Util::GetExeFileName(const char* argv0, char* buffer, int bufSize) { #ifdef WIN32 - GetModuleFileName(NULL, szBuffer, iBufSize); + GetModuleFileName(NULL, buffer, bufSize); #else // Linux - int r = readlink("/proc/self/exe", szBuffer, iBufSize-1); + int r = readlink("/proc/self/exe", buffer, bufSize-1); if (r > 0) { - szBuffer[r] = '\0'; + buffer[r] = '\0'; return; } // FreeBSD - r = readlink("/proc/curproc/file", szBuffer, iBufSize-1); + r = readlink("/proc/curproc/file", buffer, bufSize-1); if (r > 0) { - szBuffer[r] = '\0'; + buffer[r] = '\0'; return; } - ExpandFileName(argv0, szBuffer, iBufSize); + ExpandFileName(argv0, buffer, bufSize); #endif } -char* Util::FormatSize(char * szBuffer, int iBufLen, long long lFileSize) +char* Util::FormatSize(char * buffer, int bufLen, long long fileSize) { - if (lFileSize > 1024 * 1024 * 1000) + if (fileSize > 1024 * 1024 * 1000) { - snprintf(szBuffer, iBufLen, "%.2f GB", (float)((float)lFileSize / 1024 / 1024 / 1024)); + snprintf(buffer, bufLen, "%.2f GB", (float)((float)fileSize / 1024 / 1024 / 1024)); } - else if (lFileSize > 1024 * 1000) + else if (fileSize > 1024 * 1000) { - snprintf(szBuffer, iBufLen, "%.2f MB", (float)((float)lFileSize / 1024 / 1024)); + snprintf(buffer, bufLen, "%.2f MB", (float)((float)fileSize / 1024 / 1024)); } - else if (lFileSize > 1000) + else if (fileSize > 1000) { - snprintf(szBuffer, iBufLen, "%.2f KB", (float)((float)lFileSize / 1024)); + snprintf(buffer, bufLen, "%.2f KB", (float)((float)fileSize / 1024)); } - else if (lFileSize == 0) + else if (fileSize == 0) { - strncpy(szBuffer, "0 MB", iBufLen); + strncpy(buffer, "0 MB", bufLen); } else { - snprintf(szBuffer, iBufLen, "%i B", (int)lFileSize); + snprintf(buffer, bufLen, "%i B", (int)fileSize); } - szBuffer[iBufLen - 1] = '\0'; - return szBuffer; + buffer[bufLen - 1] = '\0'; + return buffer; } -char* Util::FormatSpeed(char* szBuffer, int iBufSize, int iBytesPerSecond) +char* Util::FormatSpeed(char* buffer, int bufSize, int bytesPerSecond) { - if (iBytesPerSecond >= 100 * 1024 * 1024) + if (bytesPerSecond >= 100 * 1024 * 1024) { - snprintf(szBuffer, iBufSize, "%i MB/s", iBytesPerSecond / 1024 / 1024); + snprintf(buffer, bufSize, "%i MB/s", bytesPerSecond / 1024 / 1024); } - else if (iBytesPerSecond >= 10 * 1024 * 1024) + else if (bytesPerSecond >= 10 * 1024 * 1024) { - snprintf(szBuffer, iBufSize, "%0.1f MB/s", (float)iBytesPerSecond / 1024.0 / 1024.0); + snprintf(buffer, bufSize, "%0.1f MB/s", (float)bytesPerSecond / 1024.0 / 1024.0); } - else if (iBytesPerSecond >= 1024 * 1000) + else if (bytesPerSecond >= 1024 * 1000) { - snprintf(szBuffer, iBufSize, "%0.2f MB/s", (float)iBytesPerSecond / 1024.0 / 1024.0); + snprintf(buffer, bufSize, "%0.2f MB/s", (float)bytesPerSecond / 1024.0 / 1024.0); } else { - snprintf(szBuffer, iBufSize, "%i KB/s", iBytesPerSecond / 1024); + snprintf(buffer, bufSize, "%i KB/s", bytesPerSecond / 1024); } - szBuffer[iBufSize - 1] = '\0'; - return szBuffer; + buffer[bufSize - 1] = '\0'; + return buffer; } -bool Util::SameFilename(const char* szFilename1, const char* szFilename2) +bool Util::SameFilename(const char* filename1, const char* filename2) { #ifdef WIN32 - return strcasecmp(szFilename1, szFilename2) == 0; + return strcasecmp(filename1, filename2) == 0; #else - return strcmp(szFilename1, szFilename2) == 0; + return strcmp(filename1, filename2) == 0; #endif } -bool Util::MatchFileExt(const char* szFilename, const char* szExtensionList, const char* szListSeparator) +bool Util::MatchFileExt(const char* filename, const char* extensionList, const char* listSeparator) { - int iFilenameLen = strlen(szFilename); + int filenameLen = strlen(filename); - Tokenizer tok(szExtensionList, szListSeparator); - while (const char* szExt = tok.Next()) + Tokenizer tok(extensionList, listSeparator); + while (const char* ext = tok.Next()) { - int iExtLen = strlen(szExt); - if (iFilenameLen >= iExtLen && !strcasecmp(szExt, szFilename + iFilenameLen - iExtLen)) + int extLen = strlen(ext); + if (filenameLen >= extLen && !strcasecmp(ext, filename + filenameLen - extLen)) { return true; } - if (strchr(szExt, '*') || strchr(szExt, '?')) + if (strchr(ext, '*') || strchr(ext, '?')) { - WildMask mask(szExt); - if (mask.Match(szFilename)) + WildMask mask(ext); + if (mask.Match(filename)) { return true; } @@ -1135,24 +1135,24 @@ bool Util::MatchFileExt(const char* szFilename, const char* szExtensionList, con } #ifndef WIN32 -void Util::FixExecPermission(const char* szFilename) +void Util::FixExecPermission(const char* filename) { struct stat buffer; - bool bOK = !stat(szFilename, &buffer); - if (bOK) + bool ok = !stat(filename, &buffer); + if (ok) { buffer.st_mode = buffer.st_mode | S_IXUSR | S_IXGRP | S_IXOTH; - chmod(szFilename, buffer.st_mode); + chmod(filename, buffer.st_mode); } } #endif -char* Util::GetLastErrorMessage(char* szBuffer, int iBufLen) +char* Util::GetLastErrorMessage(char* buffer, int bufLen) { - szBuffer[0] = '\0'; - strerror_r(errno, szBuffer, iBufLen); - szBuffer[iBufLen-1] = '\0'; - return szBuffer; + buffer[0] = '\0'; + strerror_r(errno, buffer, bufLen); + buffer[bufLen-1] = '\0'; + return buffer; } void Util::Init() @@ -1172,68 +1172,68 @@ void Util::Init() GetCurrentTicks(); } -bool Util::SplitCommandLine(const char* szCommandLine, char*** argv) +bool Util::SplitCommandLine(const char* commandLine, char*** argv) { - int iArgCount = 0; - char szBuf[1024]; + int argCount = 0; + char buf[1024]; char* pszArgList[100]; - unsigned int iLen = 0; - bool bEscaping = false; - bool bSpace = true; - for (const char* p = szCommandLine; ; p++) + unsigned int len = 0; + bool escaping = false; + bool space = true; + for (const char* p = commandLine; ; p++) { if (*p) { const char c = *p; - if (bEscaping) + if (escaping) { if (c == '\'') { - if (p[1] == '\'' && iLen < sizeof(szBuf) - 1) + if (p[1] == '\'' && len < sizeof(buf) - 1) { - szBuf[iLen++] = c; + buf[len++] = c; p++; } else { - bEscaping = false; - bSpace = true; + escaping = false; + space = true; } } - else if (iLen < sizeof(szBuf) - 1) + else if (len < sizeof(buf) - 1) { - szBuf[iLen++] = c; + buf[len++] = c; } } else { if (c == ' ') { - bSpace = true; + space = true; } - else if (c == '\'' && bSpace) + else if (c == '\'' && space) { - bEscaping = true; - bSpace = false; + escaping = true; + space = false; } - else if (iLen < sizeof(szBuf) - 1) + else if (len < sizeof(buf) - 1) { - szBuf[iLen++] = c; - bSpace = false; + buf[len++] = c; + space = false; } } } - if ((bSpace || !*p) && iLen > 0 && iArgCount < 100) + if ((space || !*p) && len > 0 && argCount < 100) { //add token - szBuf[iLen] = '\0'; + buf[len] = '\0'; if (argv) { - pszArgList[iArgCount] = strdup(szBuf); + pszArgList[argCount] = strdup(buf); } - (iArgCount)++; - iLen = 0; + (argCount)++; + len = 0; } if (!*p) @@ -1244,50 +1244,50 @@ bool Util::SplitCommandLine(const char* szCommandLine, char*** argv) if (argv) { - pszArgList[iArgCount] = NULL; - *argv = (char**)malloc((iArgCount + 1) * sizeof(char*)); - memcpy(*argv, pszArgList, sizeof(char*) * (iArgCount + 1)); + pszArgList[argCount] = NULL; + *argv = (char**)malloc((argCount + 1) * sizeof(char*)); + memcpy(*argv, pszArgList, sizeof(char*) * (argCount + 1)); } - return iArgCount > 0; + return argCount > 0; } -void Util::TrimRight(char* szStr) +void Util::TrimRight(char* str) { - char* szEnd = szStr + strlen(szStr) - 1; - while (szEnd >= szStr && (*szEnd == '\n' || *szEnd == '\r' || *szEnd == ' ' || *szEnd == '\t')) + char* end = str + strlen(str) - 1; + while (end >= str && (*end == '\n' || *end == '\r' || *end == ' ' || *end == '\t')) { - *szEnd = '\0'; - szEnd--; + *end = '\0'; + end--; } } -char* Util::Trim(char* szStr) +char* Util::Trim(char* str) { - TrimRight(szStr); - while (*szStr == '\n' || *szStr == '\r' || *szStr == ' ' || *szStr == '\t') + TrimRight(str); + while (*str == '\n' || *str == '\r' || *str == ' ' || *str == '\t') { - szStr++; + str++; } - return szStr; + return str; } -char* Util::ReduceStr(char* szStr, const char* szFrom, const char* szTo) +char* Util::ReduceStr(char* str, const char* from, const char* to) { - int iLenFrom = strlen(szFrom); - int iLenTo = strlen(szTo); + int lenFrom = strlen(from); + int lenTo = strlen(to); // assert(iLenTo < iLenFrom); - while (char* p = strstr(szStr, szFrom)) + while (char* p = strstr(str, from)) { - const char* src = szTo; + const char* src = to; while ((*p++ = *src++)) ; - src = --p - iLenTo + iLenFrom; + src = --p - lenTo + lenFrom; while ((*p++ = *src++)) ; } - return szStr; + return str; } /* Calculate Hash using Bob Jenkins (1996) algorithm @@ -1357,22 +1357,22 @@ ub4 hash(register ub1 *k, register ub4 length, register ub4 initval) return c; } -unsigned int Util::HashBJ96(const char* szBuffer, int iBufSize, unsigned int iInitValue) +unsigned int Util::HashBJ96(const char* buffer, int bufSize, unsigned int initValue) { - return (unsigned int)hash((ub1*)szBuffer, (ub4)iBufSize, (ub4)iInitValue); + return (unsigned int)hash((ub1*)buffer, (ub4)bufSize, (ub4)initValue); } #ifdef WIN32 -bool Util::RegReadStr(HKEY hKey, const char* szKeyName, const char* szValueName, char* szBuffer, int* iBufLen) +bool Util::RegReadStr(HKEY hKey, const char* keyName, const char* valueName, char* buffer, int* bufLen) { HKEY hSubKey; - if (!RegOpenKeyEx(hKey, szKeyName, 0, KEY_READ, &hSubKey)) + if (!RegOpenKeyEx(hKey, keyName, 0, KEY_READ, &hSubKey)) { - DWORD iRetBytes = *iBufLen; - LONG iRet = RegQueryValueEx(hSubKey, szValueName, NULL, NULL, (LPBYTE)szBuffer, &iRetBytes); - *iBufLen = iRetBytes; + DWORD retBytes = *bufLen; + LONG ret = RegQueryValueEx(hSubKey, valueName, NULL, NULL, (LPBYTE)buffer, &retBytes); + *bufLen = retBytes; RegCloseKey(hSubKey); - return iRet == 0; + return ret == 0; } return false; } @@ -1442,10 +1442,10 @@ time_t Util::Timegm(tm const *t) } // prevent PC from going to sleep -void Util::SetStandByMode(bool bStandBy) +void Util::SetStandByMode(bool standBy) { #ifdef WIN32 - SetThreadExecutionState((bStandBy ? 0 : ES_SYSTEM_REQUIRED) | ES_CONTINUOUS); + SetThreadExecutionState((standBy ? 0 : ES_SYSTEM_REQUIRED) | ES_CONTINUOUS); #endif } @@ -1613,58 +1613,58 @@ int Util::NumberOfCpuCores() return -1; } -bool Util::FlushFileBuffers(int iFileDescriptor, char* szErrBuf, int iBufSize) +bool Util::FlushFileBuffers(int fileDescriptor, char* errBuf, int bufSize) { #ifdef WIN32 - BOOL bOK = ::FlushFileBuffers((HANDLE)_get_osfhandle(iFileDescriptor)); - if (!bOK) + BOOL ok = ::FlushFileBuffers((HANDLE)_get_osfhandle(fileDescriptor)); + if (!ok) { FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - szErrBuf, iBufSize, NULL); + errBuf, bufSize, NULL); } - return bOK; + return ok; #else #ifdef HAVE_FULLFSYNC - int ret = fcntl(iFileDescriptor, F_FULLFSYNC) == -1 ? 1 : 0; + int ret = fcntl(fileDescriptor, F_FULLFSYNC) == -1 ? 1 : 0; #elif HAVE_FDATASYNC - int ret = fdatasync(iFileDescriptor); + int ret = fdatasync(fileDescriptor); #else - int ret = fsync(iFileDescriptor); + int ret = fsync(fileDescriptor); #endif if (ret != 0) { - GetLastErrorMessage(szErrBuf, iBufSize); + GetLastErrorMessage(errBuf, bufSize); } return ret == 0; #endif } -bool Util::FlushDirBuffers(const char* szFilename, char* szErrBuf, int iBufSize) +bool Util::FlushDirBuffers(const char* filename, char* errBuf, int bufSize) { - char szParentPath[1024]; - strncpy(szParentPath, szFilename, 1024); - szParentPath[1024-1] = '\0'; - const char* szFileMode = FOPEN_RBP; + char parentPath[1024]; + strncpy(parentPath, filename, 1024); + parentPath[1024-1] = '\0'; + const char* fileMode = FOPEN_RBP; #ifndef WIN32 - char* p = (char*)strrchr(szParentPath, PATH_SEPARATOR); + char* p = (char*)strrchr(parentPath, PATH_SEPARATOR); if (p) { *p = '\0'; } - szFileMode = FOPEN_RB; + fileMode = FOPEN_RB; #endif - FILE* pFile = fopen(szParentPath, szFileMode); - if (!pFile) + FILE* file = fopen(parentPath, fileMode); + if (!file) { - GetLastErrorMessage(szErrBuf, iBufSize); + GetLastErrorMessage(errBuf, bufSize); return false; } - bool bOK = FlushFileBuffers(fileno(pFile), szErrBuf, iBufSize); - fclose(pFile); - return bOK; + bool ok = FlushFileBuffers(fileno(file), errBuf, bufSize); + fclose(file); + return ok; } long long Util::GetCurrentTicks() @@ -1686,32 +1686,32 @@ long long Util::GetCurrentTicks() #endif } -unsigned int WebUtil::DecodeBase64(char* szInputBuffer, int iInputBufferLength, char* szOutputBuffer) +unsigned int WebUtil::DecodeBase64(char* inputBuffer, int inputBufferLength, char* outputBuffer) { unsigned int InputBufferIndex = 0; unsigned int OutputBufferIndex = 0; - unsigned int InputBufferLength = iInputBufferLength > 0 ? iInputBufferLength : strlen(szInputBuffer); + unsigned int InputBufferLength = inputBufferLength > 0 ? inputBufferLength : strlen(inputBuffer); char ByteQuartet [4]; int i = 0; while (InputBufferIndex < InputBufferLength) { // Ignore all characters except the ones in BASE64_ALPHABET - if ((szInputBuffer [InputBufferIndex] >= 48 && szInputBuffer [InputBufferIndex] <= 57) || - (szInputBuffer [InputBufferIndex] >= 65 && szInputBuffer [InputBufferIndex] <= 90) || - (szInputBuffer [InputBufferIndex] >= 97 && szInputBuffer [InputBufferIndex] <= 122) || - szInputBuffer [InputBufferIndex] == '+' || - szInputBuffer [InputBufferIndex] == '/' || - szInputBuffer [InputBufferIndex] == '=') + if ((inputBuffer [InputBufferIndex] >= 48 && inputBuffer [InputBufferIndex] <= 57) || + (inputBuffer [InputBufferIndex] >= 65 && inputBuffer [InputBufferIndex] <= 90) || + (inputBuffer [InputBufferIndex] >= 97 && inputBuffer [InputBufferIndex] <= 122) || + inputBuffer [InputBufferIndex] == '+' || + inputBuffer [InputBufferIndex] == '/' || + inputBuffer [InputBufferIndex] == '=') { - ByteQuartet [i] = szInputBuffer [InputBufferIndex]; + ByteQuartet [i] = inputBuffer [InputBufferIndex]; i++; } InputBufferIndex++; if (i == 4) { - OutputBufferIndex += DecodeByteQuartet(ByteQuartet, szOutputBuffer + OutputBufferIndex); + OutputBufferIndex += DecodeByteQuartet(ByteQuartet, outputBuffer + OutputBufferIndex); i = 0; } } @@ -1728,7 +1728,7 @@ unsigned int WebUtil::DecodeBase64(char* szInputBuffer, int iInputBufferLength, char* WebUtil::XmlEncode(const char* raw) { // calculate the required outputstring-size based on number of xml-entities and their sizes - int iReqSize = strlen(raw); + int reqSize = strlen(raw); for (const char* p = raw; *p; p++) { unsigned char ch = *p; @@ -1736,25 +1736,25 @@ char* WebUtil::XmlEncode(const char* raw) { case '>': case '<': - iReqSize += 4; + reqSize += 4; break; case '&': - iReqSize += 5; + reqSize += 5; break; case '\'': case '\"': - iReqSize += 6; + reqSize += 6; break; default: if (ch < 0x20 || ch >= 0x80) { - iReqSize += 10; + reqSize += 10; break; } } } - char* result = (char*)malloc(iReqSize + 1); + char* result = (char*)malloc(reqSize + 1); // copy string char* output = result; @@ -1907,60 +1907,60 @@ BreakLoop: *output = '\0'; } -const char* WebUtil::XmlFindTag(const char* szXml, const char* szTag, int* pValueLength) +const char* WebUtil::XmlFindTag(const char* xml, const char* tag, int* valueLength) { - char szOpenTag[100]; - snprintf(szOpenTag, 100, "<%s>", szTag); - szOpenTag[100-1] = '\0'; + char openTag[100]; + snprintf(openTag, 100, "<%s>", tag); + openTag[100-1] = '\0'; - char szCloseTag[100]; - snprintf(szCloseTag, 100, "", szTag); - szCloseTag[100-1] = '\0'; + char closeTag[100]; + snprintf(closeTag, 100, "", tag); + closeTag[100-1] = '\0'; - char szOpenCloseTag[100]; - snprintf(szOpenCloseTag, 100, "<%s/>", szTag); - szOpenCloseTag[100-1] = '\0'; + char openCloseTag[100]; + snprintf(openCloseTag, 100, "<%s/>", tag); + openCloseTag[100-1] = '\0'; - const char* pstart = strstr(szXml, szOpenTag); - const char* pstartend = strstr(szXml, szOpenCloseTag); + const char* pstart = strstr(xml, openTag); + const char* pstartend = strstr(xml, openCloseTag); if (!pstart && !pstartend) return NULL; if (pstartend && (!pstart || pstartend < pstart)) { - *pValueLength = 0; + *valueLength = 0; return pstartend; } - const char* pend = strstr(pstart, szCloseTag); + const char* pend = strstr(pstart, closeTag); if (!pend) return NULL; - int iTagLen = strlen(szOpenTag); - *pValueLength = (int)(pend - pstart - iTagLen); + int tagLen = strlen(openTag); + *valueLength = (int)(pend - pstart - tagLen); - return pstart + iTagLen; + return pstart + tagLen; } -bool WebUtil::XmlParseTagValue(const char* szXml, const char* szTag, char* szValueBuf, int iValueBufSize, const char** pTagEnd) +bool WebUtil::XmlParseTagValue(const char* xml, const char* tag, char* valueBuf, int valueBufSize, const char** tagEnd) { - int iValueLen = 0; - const char* szValue = XmlFindTag(szXml, szTag, &iValueLen); - if (!szValue) + int valueLen = 0; + const char* value = XmlFindTag(xml, tag, &valueLen); + if (!value) { return false; } - int iLen = iValueLen < iValueBufSize ? iValueLen : iValueBufSize - 1; - strncpy(szValueBuf, szValue, iLen); - szValueBuf[iLen] = '\0'; - if (pTagEnd) + int len = valueLen < valueBufSize ? valueLen : valueBufSize - 1; + strncpy(valueBuf, value, len); + valueBuf[len] = '\0'; + if (tagEnd) { - *pTagEnd = szValue + iValueLen; + *tagEnd = value + valueLen; } return true; } -void WebUtil::XmlStripTags(char* szXml) +void WebUtil::XmlStripTags(char* xml) { - while (char *start = strchr(szXml, '<')) + while (char *start = strchr(xml, '<')) { char *end = strchr(start, '>'); if (!end) @@ -1968,7 +1968,7 @@ void WebUtil::XmlStripTags(char* szXml) break; } memset(start, ' ', end - start + 1); - szXml = end + 1; + xml = end + 1; } } @@ -2009,7 +2009,7 @@ BreakLoop: char* WebUtil::JsonEncode(const char* raw) { // calculate the required outputstring-size based on number of escape-entities and their sizes - int iReqSize = strlen(raw); + int reqSize = strlen(raw); for (const char* p = raw; *p; p++) { unsigned char ch = *p; @@ -2023,18 +2023,18 @@ char* WebUtil::JsonEncode(const char* raw) case '\n': case '\r': case '\t': - iReqSize++; + reqSize++; break; default: if (ch < 0x20 || ch >= 0x80) { - iReqSize += 6; + reqSize += 6; break; } } } - char* result = (char*)malloc(iReqSize + 1); + char* result = (char*)malloc(reqSize + 1); // copy string char* output = result; @@ -2186,23 +2186,23 @@ BreakLoop: *output = '\0'; } -const char* WebUtil::JsonFindField(const char* szJsonText, const char* szFieldName, int* pValueLength) +const char* WebUtil::JsonFindField(const char* jsonText, const char* fieldName, int* valueLength) { - char szOpenTag[100]; - snprintf(szOpenTag, 100, "\"%s\"", szFieldName); - szOpenTag[100-1] = '\0'; + char openTag[100]; + snprintf(openTag, 100, "\"%s\"", fieldName); + openTag[100-1] = '\0'; - const char* pstart = strstr(szJsonText, szOpenTag); + const char* pstart = strstr(jsonText, openTag); if (!pstart) return NULL; - pstart += strlen(szOpenTag); + pstart += strlen(openTag); - return JsonNextValue(pstart, pValueLength); + return JsonNextValue(pstart, valueLength); } -const char* WebUtil::JsonNextValue(const char* szJsonText, int* pValueLength) +const char* WebUtil::JsonNextValue(const char* jsonText, int* valueLength) { - const char* pstart = szJsonText; + const char* pstart = jsonText; while (*pstart && strchr(" ,[{:\r\n\t\f", *pstart)) pstart++; if (!*pstart) return NULL; @@ -2210,8 +2210,8 @@ const char* WebUtil::JsonNextValue(const char* szJsonText, int* pValueLength) const char* pend = pstart; char ch = *pend; - bool bStr = ch == '"'; - if (bStr) + bool str = ch == '"'; + if (str) { ch = *++pend; } @@ -2222,19 +2222,19 @@ const char* WebUtil::JsonNextValue(const char* szJsonText, int* pValueLength) if (!*++pend || !*++pend) return NULL; ch = *pend; } - if (bStr && ch == '"') + if (str && ch == '"') { pend++; break; } - else if (!bStr && strchr(" ,]}\r\n\t\f", ch)) + else if (!str && strchr(" ,]}\r\n\t\f", ch)) { break; } ch = *++pend; } - *pValueLength = (int)(pend - pstart); + *valueLength = (int)(pend - pstart); return pstart; } @@ -2302,16 +2302,16 @@ BreakLoop: char* WebUtil::URLEncode(const char* raw) { // calculate the required outputstring-size based on number of spaces - int iReqSize = strlen(raw); + int reqSize = strlen(raw); for (const char* p = raw; *p; p++) { if (*p == ' ') { - iReqSize += 3; // length of "%20" + reqSize += 3; // length of "%20" } } - char* result = (char*)malloc(iReqSize + 1); + char* result = (char*)malloc(reqSize + 1); // copy string char* output = result; @@ -2338,35 +2338,35 @@ BreakLoop: } #ifdef WIN32 -bool WebUtil::Utf8ToAnsi(char* szBuffer, int iBufLen) +bool WebUtil::Utf8ToAnsi(char* buffer, int bufLen) { - WCHAR* wstr = (WCHAR*)malloc(iBufLen * 2); - int errcode = MultiByteToWideChar(CP_UTF8, 0, szBuffer, -1, wstr, iBufLen); + WCHAR* wstr = (WCHAR*)malloc(bufLen * 2); + int errcode = MultiByteToWideChar(CP_UTF8, 0, buffer, -1, wstr, bufLen); if (errcode > 0) { - errcode = WideCharToMultiByte(CP_ACP, 0, wstr, -1, szBuffer, iBufLen, "_", NULL); + errcode = WideCharToMultiByte(CP_ACP, 0, wstr, -1, buffer, bufLen, "_", NULL); } free(wstr); return errcode > 0; } -bool WebUtil::AnsiToUtf8(char* szBuffer, int iBufLen) +bool WebUtil::AnsiToUtf8(char* buffer, int bufLen) { - WCHAR* wstr = (WCHAR*)malloc(iBufLen * 2); - int errcode = MultiByteToWideChar(CP_ACP, 0, szBuffer, -1, wstr, iBufLen); + WCHAR* wstr = (WCHAR*)malloc(bufLen * 2); + int errcode = MultiByteToWideChar(CP_ACP, 0, buffer, -1, wstr, bufLen); if (errcode > 0) { - errcode = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, szBuffer, iBufLen, NULL, NULL); + errcode = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, buffer, bufLen, NULL, NULL); } free(wstr); return errcode > 0; } #endif -char* WebUtil::Latin1ToUtf8(const char* szStr) +char* WebUtil::Latin1ToUtf8(const char* str) { - char *res = (char*)malloc(strlen(szStr) * 2 + 1); - const unsigned char *in = (const unsigned char*)szStr; + char *res = (char*)malloc(strlen(str) * 2 + 1); + const unsigned char *in = (const unsigned char*)str; unsigned char *out = (unsigned char*)res; while (*in) { @@ -2393,11 +2393,11 @@ char* WebUtil::Latin1ToUtf8(const char* szStr) 26 Jun 2013 01:02 A This function however supports only the first format! */ -time_t WebUtil::ParseRfc822DateTime(const char* szDateTimeStr) +time_t WebUtil::ParseRfc822DateTime(const char* dateTimeStr) { char month[4]; int day, year, hours, minutes, seconds, zonehours, zoneminutes; - int r = sscanf(szDateTimeStr, "%*s %d %3s %d %d:%d:%d %3d %2d", &day, &month[0], &year, &hours, &minutes, &seconds, &zonehours, &zoneminutes); + int r = sscanf(dateTimeStr, "%*s %d %3s %d %d:%d:%d %3d %2d", &day, &month[0], &year, &hours, &minutes, &seconds, &zonehours, &zoneminutes); if (r != 8) { return 0; @@ -2434,33 +2434,33 @@ time_t WebUtil::ParseRfc822DateTime(const char* szDateTimeStr) } -URL::URL(const char* szAddress) +URL::URL(const char* address) { - m_szAddress = NULL; - m_szProtocol = NULL; - m_szUser = NULL; - m_szPassword = NULL; - m_szHost = NULL; - m_szResource = NULL; - m_iPort = 0; - m_bTLS = false; - m_bValid = false; + m_address = NULL; + m_protocol = NULL; + m_user = NULL; + m_password = NULL; + m_host = NULL; + m_resource = NULL; + m_port = 0; + m_tLS = false; + m_valid = false; - if (szAddress) + if (address) { - m_szAddress = strdup(szAddress); + m_address = strdup(address); ParseURL(); } } URL::~URL() { - free(m_szAddress); - free(m_szProtocol); - free(m_szUser); - free(m_szPassword); - free(m_szHost); - free(m_szResource); + free(m_address); + free(m_protocol); + free(m_user); + free(m_password); + free(m_host); + free(m_resource); } void URL::ParseURL() @@ -2472,16 +2472,16 @@ void URL::ParseURL() // http://host/path/to/resource?param // http://host - char* protEnd = strstr(m_szAddress, "://"); + char* protEnd = strstr(m_address, "://"); if (!protEnd) { // Bad URL return; } - m_szProtocol = (char*)malloc(protEnd - m_szAddress + 1); - strncpy(m_szProtocol, m_szAddress, protEnd - m_szAddress); - m_szProtocol[protEnd - m_szAddress] = 0; + m_protocol = (char*)malloc(protEnd - m_address + 1); + strncpy(m_protocol, m_address, protEnd - m_address); + m_protocol[protEnd - m_address] = 0; char* hostStart = protEnd + 3; char* slash = strchr(hostStart, '/'); @@ -2495,22 +2495,22 @@ void URL::ParseURL() char* pass = strchr(hostStart, ':'); if (pass && pass < amp) { - int iLen = (int)(amp - pass - 1); - if (iLen > 0) + int len = (int)(amp - pass - 1); + if (len > 0) { - m_szPassword = (char*)malloc(iLen + 1); - strncpy(m_szPassword, pass + 1, iLen); - m_szPassword[iLen] = 0; + m_password = (char*)malloc(len + 1); + strncpy(m_password, pass + 1, len); + m_password[len] = 0; } userend = pass - 1; } - int iLen = (int)(userend - hostStart + 1); - if (iLen > 0) + int len = (int)(userend - hostStart + 1); + if (len > 0) { - m_szUser = (char*)malloc(iLen + 1); - strncpy(m_szUser, hostStart, iLen); - m_szUser[iLen] = 0; + m_user = (char*)malloc(len + 1); + strncpy(m_user, hostStart, len); + m_user[len] = 0; } hostStart = amp + 1; @@ -2518,66 +2518,66 @@ void URL::ParseURL() if (slash) { - char* resEnd = m_szAddress + strlen(m_szAddress); - m_szResource = (char*)malloc(resEnd - slash + 1 + 1); - strncpy(m_szResource, slash, resEnd - slash + 1); - m_szResource[resEnd - slash + 1] = 0; + char* resEnd = m_address + strlen(m_address); + m_resource = (char*)malloc(resEnd - slash + 1 + 1); + strncpy(m_resource, slash, resEnd - slash + 1); + m_resource[resEnd - slash + 1] = 0; hostEnd = slash - 1; } else { - m_szResource = strdup("/"); + m_resource = strdup("/"); - hostEnd = m_szAddress + strlen(m_szAddress); + hostEnd = m_address + strlen(m_address); } char* colon = strchr(hostStart, ':'); if (colon && colon < hostEnd) { hostEnd = colon - 1; - m_iPort = atoi(colon + 1); + m_port = atoi(colon + 1); } - m_szHost = (char*)malloc(hostEnd - hostStart + 1 + 1); - strncpy(m_szHost, hostStart, hostEnd - hostStart + 1); - m_szHost[hostEnd - hostStart + 1] = 0; + m_host = (char*)malloc(hostEnd - hostStart + 1 + 1); + strncpy(m_host, hostStart, hostEnd - hostStart + 1); + m_host[hostEnd - hostStart + 1] = 0; - m_bValid = true; + m_valid = true; } -RegEx::RegEx(const char *szPattern, int iMatchBufSize) +RegEx::RegEx(const char *pattern, int matchBufSize) { #ifdef HAVE_REGEX_H - m_pContext = malloc(sizeof(regex_t)); - m_bValid = regcomp((regex_t*)m_pContext, szPattern, REG_EXTENDED | REG_ICASE | (iMatchBufSize > 0 ? 0 : REG_NOSUB)) == 0; - m_iMatchBufSize = iMatchBufSize; - if (iMatchBufSize > 0) + m_context = malloc(sizeof(regex_t)); + m_valid = regcomp((regex_t*)m_context, pattern, REG_EXTENDED | REG_ICASE | (matchBufSize > 0 ? 0 : REG_NOSUB)) == 0; + m_matchBufSize = matchBufSize; + if (matchBufSize > 0) { - m_pMatches = malloc(sizeof(regmatch_t) * iMatchBufSize); + m_matches = malloc(sizeof(regmatch_t) * matchBufSize); } else { - m_pMatches = NULL; + m_matches = NULL; } #else - m_bValid = false; + m_valid = false; #endif } RegEx::~RegEx() { #ifdef HAVE_REGEX_H - regfree((regex_t*)m_pContext); - free(m_pContext); - free(m_pMatches); + regfree((regex_t*)m_context); + free(m_context); + free(m_matches); #endif } -bool RegEx::Match(const char *szStr) +bool RegEx::Match(const char *str) { #ifdef HAVE_REGEX_H - return m_bValid ? regexec((regex_t*)m_pContext, szStr, m_iMatchBufSize, (regmatch_t*)m_pMatches, 0) == 0 : false; + return m_valid ? regexec((regex_t*)m_context, str, m_matchBufSize, (regmatch_t*)m_matches, 0) == 0 : false; #else return false; #endif @@ -2586,16 +2586,16 @@ bool RegEx::Match(const char *szStr) int RegEx::GetMatchCount() { #ifdef HAVE_REGEX_H - int iCount = 0; - if (m_pMatches) + int count = 0; + if (m_matches) { - regmatch_t* pMatches = (regmatch_t*)m_pMatches; - while (iCount < m_iMatchBufSize && pMatches[iCount].rm_so > -1) + regmatch_t* matches = (regmatch_t*)m_matches; + while (count < m_matchBufSize && matches[count].rm_so > -1) { - iCount++; + count++; } } - return iCount; + return count; #else return 0; #endif @@ -2604,8 +2604,8 @@ int RegEx::GetMatchCount() int RegEx::GetMatchStart(int index) { #ifdef HAVE_REGEX_H - regmatch_t* pMatches = (regmatch_t*)m_pMatches; - return pMatches[index].rm_so; + regmatch_t* matches = (regmatch_t*)m_matches; + return matches[index].rm_so; #else return NULL; #endif @@ -2614,68 +2614,68 @@ int RegEx::GetMatchStart(int index) int RegEx::GetMatchLen(int index) { #ifdef HAVE_REGEX_H - regmatch_t* pMatches = (regmatch_t*)m_pMatches; - return pMatches[index].rm_eo - pMatches[index].rm_so; + regmatch_t* matches = (regmatch_t*)m_matches; + return matches[index].rm_eo - matches[index].rm_so; #else return 0; #endif } -WildMask::WildMask(const char *szPattern, bool bWantsPositions) +WildMask::WildMask(const char *pattern, bool wantsPositions) { - m_szPattern = strdup(szPattern); - m_bWantsPositions = bWantsPositions; - m_WildStart = NULL; - m_WildLen = NULL; - m_iArrLen = 0; + m_pattern = strdup(pattern); + m_wantsPositions = wantsPositions; + m_wildStart = NULL; + m_wildLen = NULL; + m_arrLen = 0; } WildMask::~WildMask() { - free(m_szPattern); - free(m_WildStart); - free(m_WildLen); + free(m_pattern); + free(m_wildStart); + free(m_wildLen); } void WildMask::ExpandArray() { - m_iWildCount++; - if (m_iWildCount > m_iArrLen) + m_wildCount++; + if (m_wildCount > m_arrLen) { - m_iArrLen += 100; - m_WildStart = (int*)realloc(m_WildStart, sizeof(*m_WildStart) * m_iArrLen); - m_WildLen = (int*)realloc(m_WildLen, sizeof(*m_WildLen) * m_iArrLen); + m_arrLen += 100; + m_wildStart = (int*)realloc(m_wildStart, sizeof(*m_wildStart) * m_arrLen); + m_wildLen = (int*)realloc(m_wildLen, sizeof(*m_wildLen) * m_arrLen); } } // Based on code from http://bytes.com/topic/c/answers/212179-string-matching // Extended to save positions of matches. -bool WildMask::Match(const char *szStr) +bool WildMask::Match(const char* text) { - const char* pat = m_szPattern; - const char* str = szStr; + const char* pat = m_pattern; + const char* str = text; const char *spos, *wpos; - m_iWildCount = 0; + m_wildCount = 0; bool qmark = false; bool star = false; spos = wpos = str; while (*str && *pat != '*') { - if (m_bWantsPositions && (*pat == '?' || *pat == '#')) + if (m_wantsPositions && (*pat == '?' || *pat == '#')) { if (!qmark) { ExpandArray(); - m_WildStart[m_iWildCount-1] = str - szStr; - m_WildLen[m_iWildCount-1] = 0; + m_wildStart[m_wildCount-1] = str - text; + m_wildLen[m_wildCount-1] = 0; qmark = true; } } - else if (m_bWantsPositions && qmark) + else if (m_wantsPositions && qmark) { - m_WildLen[m_iWildCount-1] = str - (szStr + m_WildStart[m_iWildCount-1]); + m_wildLen[m_wildCount-1] = str - (text + m_wildStart[m_wildCount-1]); qmark = false; } @@ -2688,9 +2688,9 @@ bool WildMask::Match(const char *szStr) pat++; } - if (m_bWantsPositions && qmark) + if (m_wantsPositions && qmark) { - m_WildLen[m_iWildCount-1] = str - (szStr + m_WildStart[m_iWildCount-1]); + m_wildLen[m_wildCount-1] = str - (text + m_wildStart[m_wildCount-1]); qmark = false; } @@ -2698,24 +2698,24 @@ bool WildMask::Match(const char *szStr) { if (*pat == '*') { - if (m_bWantsPositions && qmark) + if (m_wantsPositions && qmark) { - m_WildLen[m_iWildCount-1] = str - (szStr + m_WildStart[m_iWildCount-1]); + m_wildLen[m_wildCount-1] = str - (text + m_wildStart[m_wildCount-1]); qmark = false; } - if (m_bWantsPositions && !star) + if (m_wantsPositions && !star) { ExpandArray(); - m_WildStart[m_iWildCount-1] = str - szStr; - m_WildLen[m_iWildCount-1] = 0; + m_wildStart[m_wildCount-1] = str - text; + m_wildLen[m_wildCount-1] = 0; star = true; } if (*++pat == '\0') { - if (m_bWantsPositions && star) + if (m_wantsPositions && star) { - m_WildLen[m_iWildCount-1] = strlen(str); + m_wildLen[m_wildCount-1] = strlen(str); } return true; @@ -2725,11 +2725,11 @@ bool WildMask::Match(const char *szStr) } else if (*pat == '?' || (*pat == '#' && strchr("0123456789", *str))) { - if (m_bWantsPositions && !qmark) + if (m_wantsPositions && !qmark) { ExpandArray(); - m_WildStart[m_iWildCount-1] = str - szStr; - m_WildLen[m_iWildCount-1] = 0; + m_wildStart[m_wildCount-1] = str - text; + m_wildLen[m_wildCount-1] = 0; qmark = true; } @@ -2738,14 +2738,14 @@ bool WildMask::Match(const char *szStr) } else if (tolower(*pat) == tolower(*str)) { - if (m_bWantsPositions && qmark) + if (m_wantsPositions && qmark) { - m_WildLen[m_iWildCount-1] = str - (szStr + m_WildStart[m_iWildCount-1]); + m_wildLen[m_wildCount-1] = str - (text + m_wildStart[m_wildCount-1]); qmark = false; } - else if (m_bWantsPositions && star) + else if (m_wantsPositions && star) { - m_WildLen[m_iWildCount-1] = str - (szStr + m_WildStart[m_iWildCount-1]); + m_wildLen[m_wildCount-1] = str - (text + m_wildStart[m_wildCount-1]); star = false; } @@ -2754,9 +2754,9 @@ bool WildMask::Match(const char *szStr) } else { - if (m_bWantsPositions && qmark) + if (m_wantsPositions && qmark) { - m_iWildCount--; + m_wildCount--; qmark = false; } @@ -2766,16 +2766,16 @@ bool WildMask::Match(const char *szStr) } } - if (m_bWantsPositions && qmark) + if (m_wantsPositions && qmark) { - m_WildLen[m_iWildCount-1] = str - (szStr + m_WildStart[m_iWildCount-1]); + m_wildLen[m_wildCount-1] = str - (text + m_wildStart[m_wildCount-1]); } - if (*pat == '*' && m_bWantsPositions && !star) + if (*pat == '*' && m_wantsPositions && !star) { ExpandArray(); - m_WildStart[m_iWildCount-1] = str - szStr; - m_WildLen[m_iWildCount-1] = strlen(str); + m_wildStart[m_wildCount-1] = str - text; + m_wildLen[m_wildCount-1] = strlen(str); } while (*pat == '*') @@ -2788,23 +2788,23 @@ bool WildMask::Match(const char *szStr) #ifndef DISABLE_GZIP -unsigned int ZLib::GZipLen(int iInputBufferLength) +unsigned int ZLib::GZipLen(int inputBufferLength) { z_stream zstr; memset(&zstr, 0, sizeof(zstr)); - return (unsigned int)deflateBound(&zstr, iInputBufferLength); + return (unsigned int)deflateBound(&zstr, inputBufferLength); } -unsigned int ZLib::GZip(const void* szInputBuffer, int iInputBufferLength, void* szOutputBuffer, int iOutputBufferLength) +unsigned int ZLib::GZip(const void* inputBuffer, int inputBufferLength, void* outputBuffer, int outputBufferLength) { z_stream zstr; zstr.zalloc = Z_NULL; zstr.zfree = Z_NULL; zstr.opaque = Z_NULL; - zstr.next_in = (Bytef*)szInputBuffer; - zstr.avail_in = iInputBufferLength; - zstr.next_out = (Bytef*)szOutputBuffer; - zstr.avail_out = iOutputBufferLength; + zstr.next_in = (Bytef*)inputBuffer; + zstr.avail_in = inputBufferLength; + zstr.next_out = (Bytef*)outputBuffer; + zstr.avail_out = outputBufferLength; /* add 16 to MAX_WBITS to enforce gzip format */ if (Z_OK != deflateInit2(&zstr, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) @@ -2825,57 +2825,57 @@ unsigned int ZLib::GZip(const void* szInputBuffer, int iInputBufferLength, void* GUnzipStream::GUnzipStream(int BufferSize) { - m_iBufferSize = BufferSize; - m_pZStream = malloc(sizeof(z_stream)); - m_pOutputBuffer = malloc(BufferSize); + m_bufferSize = BufferSize; + m_zStream = malloc(sizeof(z_stream)); + m_outputBuffer = malloc(BufferSize); - memset(m_pZStream, 0, sizeof(z_stream)); + memset(m_zStream, 0, sizeof(z_stream)); /* add 16 to MAX_WBITS to enforce gzip format */ - int ret = inflateInit2(((z_stream*)m_pZStream), MAX_WBITS + 16); + int ret = inflateInit2(((z_stream*)m_zStream), MAX_WBITS + 16); if (ret != Z_OK) { - free(m_pZStream); - m_pZStream = NULL; + free(m_zStream); + m_zStream = NULL; } } GUnzipStream::~GUnzipStream() { - if (m_pZStream) + if (m_zStream) { - inflateEnd(((z_stream*)m_pZStream)); - free(m_pZStream); + inflateEnd(((z_stream*)m_zStream)); + free(m_zStream); } - free(m_pOutputBuffer); + free(m_outputBuffer); } -void GUnzipStream::Write(const void *pInputBuffer, int iInputBufferLength) +void GUnzipStream::Write(const void *inputBuffer, int inputBufferLength) { - ((z_stream*)m_pZStream)->next_in = (Bytef*)pInputBuffer; - ((z_stream*)m_pZStream)->avail_in = iInputBufferLength; + ((z_stream*)m_zStream)->next_in = (Bytef*)inputBuffer; + ((z_stream*)m_zStream)->avail_in = inputBufferLength; } -GUnzipStream::EStatus GUnzipStream::Read(const void **pOutputBuffer, int *iOutputBufferLength) +GUnzipStream::EStatus GUnzipStream::Read(const void **outputBuffer, int *outputBufferLength) { - ((z_stream*)m_pZStream)->next_out = (Bytef*)m_pOutputBuffer; - ((z_stream*)m_pZStream)->avail_out = m_iBufferSize; + ((z_stream*)m_zStream)->next_out = (Bytef*)m_outputBuffer; + ((z_stream*)m_zStream)->avail_out = m_bufferSize; - *iOutputBufferLength = 0; + *outputBufferLength = 0; - if (!m_pZStream) + if (!m_zStream) { return zlError; } - int ret = inflate(((z_stream*)m_pZStream), Z_NO_FLUSH); + int ret = inflate(((z_stream*)m_zStream), Z_NO_FLUSH); switch (ret) { case Z_STREAM_END: case Z_OK: - *iOutputBufferLength = m_iBufferSize - ((z_stream*)m_pZStream)->avail_out; - *pOutputBuffer = m_pOutputBuffer; + *outputBufferLength = m_bufferSize - ((z_stream*)m_zStream)->avail_out; + *outputBuffer = m_outputBuffer; return ret == Z_STREAM_END ? zlFinished : zlOK; case Z_BUF_ERROR: @@ -2887,57 +2887,57 @@ GUnzipStream::EStatus GUnzipStream::Read(const void **pOutputBuffer, int *iOutpu #endif -Tokenizer::Tokenizer(const char* szDataString, const char* szSeparators) +Tokenizer::Tokenizer(const char* dataString, const char* separators) { // an optimization to avoid memory allocation for short data string (shorten than 1024 chars) - int iLen = strlen(szDataString); - if (iLen < sizeof(m_szDefaultBuf) - 1) + int len = strlen(dataString); + if (len < sizeof(m_defaultBuf) - 1) { - strncpy(m_szDefaultBuf, szDataString, sizeof(m_szDefaultBuf)); - m_szDefaultBuf[1024- 1] = '\0'; - m_szDataString = m_szDefaultBuf; - m_bInplaceBuf = true; + strncpy(m_defaultBuf, dataString, sizeof(m_defaultBuf)); + m_defaultBuf[1024- 1] = '\0'; + m_dataString = m_defaultBuf; + m_inplaceBuf = true; } else { - m_szDataString = strdup(szDataString); - m_bInplaceBuf = false; + m_dataString = strdup(dataString); + m_inplaceBuf = false; } - m_szSeparators = szSeparators; - m_szSavePtr = NULL; - m_bWorking = false; + m_separators = separators; + m_savePtr = NULL; + m_working = false; } -Tokenizer::Tokenizer(char* szDataString, const char* szSeparators, bool bInplaceBuf) +Tokenizer::Tokenizer(char* dataString, const char* separators, bool inplaceBuf) { - m_szDataString = bInplaceBuf ? szDataString : strdup(szDataString); - m_szSeparators = szSeparators; - m_szSavePtr = NULL; - m_bWorking = false; - m_bInplaceBuf = bInplaceBuf; + m_dataString = inplaceBuf ? dataString : strdup(dataString); + m_separators = separators; + m_savePtr = NULL; + m_working = false; + m_inplaceBuf = inplaceBuf; } Tokenizer::~Tokenizer() { - if (!m_bInplaceBuf) + if (!m_inplaceBuf) { - free(m_szDataString); + free(m_dataString); } } char* Tokenizer::Next() { - char* szToken = NULL; - while (!szToken || !*szToken) + char* token = NULL; + while (!token || !*token) { - szToken = strtok_r(m_bWorking ? NULL : m_szDataString, m_szSeparators, &m_szSavePtr); - m_bWorking = true; - if (!szToken) + token = strtok_r(m_working ? NULL : m_dataString, m_separators, &m_savePtr); + m_working = true; + if (!token) { return NULL; } - szToken = Util::Trim(szToken); + token = Util::Trim(token); } - return szToken; + return token; } diff --git a/daemon/util/Util.h b/daemon/util/Util.h index 7bcfbb58..613975a9 100644 --- a/daemon/util/Util.h +++ b/daemon/util/Util.h @@ -42,26 +42,26 @@ class DirBrowser { private: #ifdef WIN32 - WIN32_FIND_DATA m_FindData; + WIN32_FIND_DATA m_findData; HANDLE m_hFile; - bool m_bFirst; + bool m_first; #else - void* m_pDir; // DIR*, declared as void* to avoid including of - struct dirent* m_pFindData; + void* m_dir; // DIR*, declared as void* to avoid including of + struct dirent* m_findData; #endif #ifdef DIRBROWSER_SNAPSHOT - bool m_bSnapshot; + bool m_snapshot; typedef std::deque FileList; - FileList m_Snapshot; + FileList m_snapshot; FileList::iterator m_itSnapshot; #endif public: #ifdef DIRBROWSER_SNAPSHOT - DirBrowser(const char* szPath, bool bSnapshot = true); + DirBrowser(const char* path, bool snapshot = true); #else - DirBrowser(const char* szPath); + DirBrowser(const char* path); #endif ~DirBrowser(); const char* Next(); @@ -70,22 +70,22 @@ public: class StringBuilder { private: - char* m_szBuffer; - int m_iBufferSize; - int m_iUsedSize; - int m_iGrowSize; + char* m_buffer; + int m_bufferSize; + int m_usedSize; + int m_growSize; - void Reserve(int iSize); + void Reserve(int size); public: StringBuilder(); ~StringBuilder(); - void Append(const char* szStr); - void AppendFmt(const char* szFormat, ...); - void AppendFmtV(const char* szFormat, va_list ap); - const char* GetBuffer() { return m_szBuffer; } - void SetGrowSize(int iGrowSize) { m_iGrowSize = iGrowSize; } - int GetUsedSize() { return m_iUsedSize; } + void Append(const char* str); + void AppendFmt(const char* format, ...); + void AppendFmtV(const char* format, va_list ap); + const char* GetBuffer() { return m_buffer; } + void SetGrowSize(int growSize) { m_growSize = growSize; } + int GetUsedSize() { return m_usedSize; } void Clear(); }; @@ -93,46 +93,46 @@ class Util { public: static char* BaseFileName(const char* filename); - static void NormalizePathSeparators(char* szPath); - static bool LoadFileIntoBuffer(const char* szFileName, char** pBuffer, int* pBufferLength); - static bool SaveBufferIntoFile(const char* szFileName, const char* szBuffer, int iBufLen); - static bool CreateSparseFile(const char* szFilename, long long iSize, char* szErrBuf, int iBufSize); - static bool TruncateFile(const char* szFilename, int iSize); - static void MakeValidFilename(char* szFilename, char cReplaceChar, bool bAllowSlashes); - static bool MakeUniqueFilename(char* szDestBufFilename, int iDestBufSize, const char* szDestDir, const char* szBasename); - static bool MoveFile(const char* szSrcFilename, const char* szDstFilename); - static bool CopyFile(const char* szSrcFilename, const char* szDstFilename); - static bool FileExists(const char* szFilename); - static bool FileExists(const char* szPath, const char* szFilenameWithoutPath); - static bool DirectoryExists(const char* szDirFilename); - static bool CreateDirectory(const char* szDirFilename); - static bool RemoveDirectory(const char* szDirFilename); - static bool DeleteDirectoryWithContent(const char* szDirFilename, char* szErrBuf, int iBufSize); - static bool ForceDirectories(const char* szPath, char* szErrBuf, int iBufSize); - static bool GetCurrentDirectory(char* szBuffer, int iBufSize); - static bool SetCurrentDirectory(const char* szDirFilename); - static long long FileSize(const char* szFilename); - static long long FreeDiskSize(const char* szPath); - static bool DirEmpty(const char* szDirFilename); - static bool RenameBak(const char* szFilename, const char* szBakPart, bool bRemoveOldExtension, char* szNewNameBuf, int iNewNameBufSize); + static void NormalizePathSeparators(char* path); + static bool LoadFileIntoBuffer(const char* fileName, char** buffer, int* bufferLength); + static bool SaveBufferIntoFile(const char* fileName, const char* buffer, int bufLen); + static bool CreateSparseFile(const char* filename, long long size, char* errBuf, int bufSize); + static bool TruncateFile(const char* filename, int size); + static void MakeValidFilename(char* filename, char cReplaceChar, bool allowSlashes); + static bool MakeUniqueFilename(char* destBufFilename, int destBufSize, const char* destDir, const char* basename); + static bool MoveFile(const char* srcFilename, const char* dstFilename); + static bool CopyFile(const char* srcFilename, const char* dstFilename); + static bool FileExists(const char* filename); + static bool FileExists(const char* path, const char* filenameWithoutPath); + static bool DirectoryExists(const char* dirFilename); + static bool CreateDirectory(const char* dirFilename); + static bool RemoveDirectory(const char* dirFilename); + static bool DeleteDirectoryWithContent(const char* dirFilename, char* errBuf, int bufSize); + static bool ForceDirectories(const char* path, char* errBuf, int bufSize); + static bool GetCurrentDirectory(char* buffer, int bufSize); + static bool SetCurrentDirectory(const char* dirFilename); + static long long FileSize(const char* filename); + static long long FreeDiskSize(const char* path); + static bool DirEmpty(const char* dirFilename); + static bool RenameBak(const char* filename, const char* bakPart, bool removeOldExtension, char* newNameBuf, int newNameBufSize); #ifndef WIN32 - static bool ExpandHomePath(const char* szFilename, char* szBuffer, int iBufSize); - static void FixExecPermission(const char* szFilename); + static bool ExpandHomePath(const char* filename, char* buffer, int bufSize); + static void FixExecPermission(const char* filename); #endif - static void ExpandFileName(const char* szFilename, char* szBuffer, int iBufSize); - static void GetExeFileName(const char* argv0, char* szBuffer, int iBufSize); - static char* FormatSpeed(char* szBuffer, int iBufSize, int iBytesPerSecond); - static char* FormatSize(char* szBuffer, int iBufLen, long long lFileSize); - static bool SameFilename(const char* szFilename1, const char* szFilename2); - static bool MatchFileExt(const char* szFilename, const char* szExtensionList, const char* szListSeparator); - static char* GetLastErrorMessage(char* szBuffer, int iBufLen); + static void ExpandFileName(const char* filename, char* buffer, int bufSize); + static void GetExeFileName(const char* argv0, char* buffer, int bufSize); + static char* FormatSpeed(char* buffer, int bufSize, int bytesPerSecond); + static char* FormatSize(char* buffer, int bufLen, long long fileSize); + static bool SameFilename(const char* filename1, const char* filename2); + static bool MatchFileExt(const char* filename, const char* extensionList, const char* listSeparator); + static char* GetLastErrorMessage(char* buffer, int bufLen); static long long GetCurrentTicks(); /* Flush disk buffers for file with given descriptor */ - static bool FlushFileBuffers(int iFileDescriptor, char* szErrBuf, int iBufSize); + static bool FlushFileBuffers(int fileDescriptor, char* errBuf, int bufSize); /* Flush disk buffers for file metadata (after file renaming) */ - static bool FlushDirBuffers(const char* szFilename, char* szErrBuf, int iBufSize); + static bool FlushDirBuffers(const char* filename, char* errBuf, int bufSize); /* * Split command line int arguments. @@ -146,26 +146,26 @@ public: * If these restrictions are exceeded, only first 100 arguments and only first 1024 * for each argument are returned (the functions still returns "true"). */ - static bool SplitCommandLine(const char* szCommandLine, char*** argv); + static bool SplitCommandLine(const char* commandLine, char*** argv); static long long JoinInt64(unsigned long Hi, unsigned long Lo); static void SplitInt64(long long Int64, unsigned long* Hi, unsigned long* Lo); - static void TrimRight(char* szStr); - static char* Trim(char* szStr); - static bool EmptyStr(const char* szStr) { return !szStr || !*szStr; } + static void TrimRight(char* str); + static char* Trim(char* str); + static bool EmptyStr(const char* str) { return !str || !*str; } /* replace all occurences of szFrom to szTo in string szStr with a limitation that szTo must be shorter than szFrom */ - static char* ReduceStr(char* szStr, const char* szFrom, const char* szTo); + static char* ReduceStr(char* str, const char* from, const char* to); /* Calculate Hash using Bob Jenkins (1996) algorithm */ - static unsigned int HashBJ96(const char* szBuffer, int iBufSize, unsigned int iInitValue); + static unsigned int HashBJ96(const char* buffer, int bufSize, unsigned int initValue); #ifdef WIN32 - static bool RegReadStr(HKEY hKey, const char* szKeyName, const char* szValueName, char* szBuffer, int* iBufLen); + static bool RegReadStr(HKEY hKey, const char* keyName, const char* valueName, char* buffer, int* bufLen); #endif - static void SetStandByMode(bool bStandBy); + static void SetStandByMode(bool standBy); /* cross platform version of GNU timegm, which is similar to mktime but takes an UTC time as parameter */ static time_t Timegm(tm const *t); @@ -193,7 +193,7 @@ public: class WebUtil { public: - static unsigned int DecodeBase64(char* szInputBuffer, int iInputBufferLength, char* szOutputBuffer); + static unsigned int DecodeBase64(char* inputBuffer, int inputBufferLength, char* outputBuffer); /* * Encodes string to be used as content of xml-tag. @@ -211,18 +211,18 @@ public: * Returns pointer to tag-content and length of content in iValueLength * The returned pointer points to the part of source-string, no additional strings are allocated. */ - static const char* XmlFindTag(const char* szXml, const char* szTag, int* pValueLength); + static const char* XmlFindTag(const char* xml, const char* tag, int* valueLength); /* * Parses tag-content into szValueBuf. */ - static bool XmlParseTagValue(const char* szXml, const char* szTag, char* szValueBuf, int iValueBufSize, const char** pTagEnd); + static bool XmlParseTagValue(const char* xml, const char* tag, char* valueBuf, int valueBufSize, const char** tagEnd); /* * Replaces all tags with spaces effectively providing the text content only. * The string is transformed in-place overwriting the previous content. */ - static void XmlStripTags(char* szXml); + static void XmlStripTags(char* xml); /* * Replaces all entities with spaces. @@ -246,13 +246,13 @@ public: * Returns pointer to field-content and length of content in iValueLength * The returned pointer points to the part of source-string, no additional strings are allocated. */ - static const char* JsonFindField(const char* szJsonText, const char* szFieldName, int* pValueLength); + static const char* JsonFindField(const char* jsonText, const char* fieldName, int* valueLength); /* * Returns pointer to field-content and length of content in iValueLength * The returned pointer points to the part of source-string, no additional strings are allocated. */ - static const char* JsonNextValue(const char* szJsonText, int* pValueLength); + static const char* JsonNextValue(const char* jsonText, int* valueLength); /* * Unquote http quoted string. @@ -273,60 +273,60 @@ public: static char* URLEncode(const char* raw); #ifdef WIN32 - static bool Utf8ToAnsi(char* szBuffer, int iBufLen); - static bool AnsiToUtf8(char* szBuffer, int iBufLen); + static bool Utf8ToAnsi(char* buffer, int bufLen); + static bool AnsiToUtf8(char* buffer, int bufLen); #endif /* * Converts ISO-8859-1 (aka Latin-1) into UTF-8. * Returns new string allocated with malloc, it needs to be freed by caller. */ - static char* Latin1ToUtf8(const char* szStr); + static char* Latin1ToUtf8(const char* str); - static time_t ParseRfc822DateTime(const char* szDateTimeStr); + static time_t ParseRfc822DateTime(const char* dateTimeStr); }; class URL { private: - char* m_szAddress; - char* m_szProtocol; - char* m_szUser; - char* m_szPassword; - char* m_szHost; - char* m_szResource; - int m_iPort; - bool m_bTLS; - bool m_bValid; + char* m_address; + char* m_protocol; + char* m_user; + char* m_password; + char* m_host; + char* m_resource; + int m_port; + bool m_tLS; + bool m_valid; void ParseURL(); public: - URL(const char* szAddress); + URL(const char* address); ~URL(); - bool IsValid() { return m_bValid; } - const char* GetAddress() { return m_szAddress; } - const char* GetProtocol() { return m_szProtocol; } - const char* GetUser() { return m_szUser; } - const char* GetPassword() { return m_szPassword; } - const char* GetHost() { return m_szHost; } - const char* GetResource() { return m_szResource; } - int GetPort() { return m_iPort; } - bool GetTLS() { return m_bTLS; } + bool IsValid() { return m_valid; } + const char* GetAddress() { return m_address; } + const char* GetProtocol() { return m_protocol; } + const char* GetUser() { return m_user; } + const char* GetPassword() { return m_password; } + const char* GetHost() { return m_host; } + const char* GetResource() { return m_resource; } + int GetPort() { return m_port; } + bool GetTLS() { return m_tLS; } }; class RegEx { private: - void* m_pContext; - bool m_bValid; - void* m_pMatches; - int m_iMatchBufSize; + void* m_context; + bool m_valid; + void* m_matches; + int m_matchBufSize; public: - RegEx(const char *szPattern, int iMatchBufSize = 100); + RegEx(const char *pattern, int matchBufSize = 100); ~RegEx(); - bool IsValid() { return m_bValid; } - bool Match(const char *szStr); + bool IsValid() { return m_valid; } + bool Match(const char *str); int GetMatchCount(); int GetMatchStart(int index); int GetMatchLen(int index); @@ -335,22 +335,22 @@ public: class WildMask { private: - char* m_szPattern; - bool m_bWantsPositions; - int m_iWildCount; - int* m_WildStart; - int* m_WildLen; - int m_iArrLen; + char* m_pattern; + bool m_wantsPositions; + int m_wildCount; + int* m_wildStart; + int* m_wildLen; + int m_arrLen; void ExpandArray(); public: - WildMask(const char *szPattern, bool bWantsPositions = false); + WildMask(const char* pattern, bool wantsPositions = false); ~WildMask(); - bool Match(const char *szStr); - int GetMatchCount() { return m_iWildCount; } - int GetMatchStart(int index) { return m_WildStart[index]; } - int GetMatchLen(int index) { return m_WildLen[index]; } + bool Match(const char* text); + int GetMatchCount() { return m_wildCount; } + int GetMatchStart(int index) { return m_wildStart[index]; } + int GetMatchLen(int index) { return m_wildLen[index]; } }; #ifndef DISABLE_GZIP @@ -360,12 +360,12 @@ public: /* * calculates the size required for output buffer */ - static unsigned int GZipLen(int iInputBufferLength); + static unsigned int GZipLen(int inputBufferLength); /* * returns the size of bytes written to szOutputBuffer or 0 if the buffer is too small or an error occured. */ - static unsigned int GZip(const void* szInputBuffer, int iInputBufferLength, void* szOutputBuffer, int iOutputBufferLength); + static unsigned int GZip(const void* inputBuffer, int inputBufferLength, void* outputBuffer, int outputBufferLength); }; class GUnzipStream @@ -379,9 +379,9 @@ public: }; private: - void* m_pZStream; - void* m_pOutputBuffer; - int m_iBufferSize; + void* m_zStream; + void* m_outputBuffer; + int m_bufferSize; public: GUnzipStream(int BufferSize); @@ -390,29 +390,29 @@ public: /* * set next memory block for uncompression */ - void Write(const void *pInputBuffer, int iInputBufferLength); + void Write(const void *inputBuffer, int inputBufferLength); /* * get next uncompressed memory block. * iOutputBufferLength - the size of uncompressed block. if it is "0" the next compressed block must be provided via "Write". */ - EStatus Read(const void **pOutputBuffer, int *iOutputBufferLength); + EStatus Read(const void **outputBuffer, int *outputBufferLength); }; #endif class Tokenizer { private: - char m_szDefaultBuf[2014]; - char* m_szDataString; - bool m_bInplaceBuf; - const char* m_szSeparators; - char* m_szSavePtr; - bool m_bWorking; + char m_defaultBuf[2014]; + char* m_dataString; + bool m_inplaceBuf; + const char* m_separators; + char* m_savePtr; + bool m_working; public: - Tokenizer(const char* szDataString, const char* szSeparators); - Tokenizer(char* szDataString, const char* szSeparators, bool bInplaceBuf); + Tokenizer(const char* dataString, const char* separators); + Tokenizer(char* dataString, const char* separators, bool inplaceBuf); ~Tokenizer(); char* Next(); }; diff --git a/daemon/windows/NTService.cpp b/daemon/windows/NTService.cpp index 05dd8e10..6cc21be5 100644 --- a/daemon/windows/NTService.cpp +++ b/daemon/windows/NTService.cpp @@ -134,19 +134,19 @@ void InstallService(int argc, char *argv[]) return; } - char szExeName[1024]; - GetModuleFileName(NULL, szExeName, 1024); - szExeName[1024-1] = '\0'; + char exeName[1024]; + GetModuleFileName(NULL, exeName, 1024); + exeName[1024-1] = '\0'; - char szCmdLine[1024]; - snprintf(szCmdLine, 1024, "%s -D", szExeName); - szCmdLine[1024-1] = '\0'; + char cmdLine[1024]; + snprintf(cmdLine, 1024, "%s -D", exeName); + cmdLine[1024-1] = '\0'; SC_HANDLE hService = CreateService(scm, strServiceName, strServiceName, SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, - szCmdLine, + cmdLine, 0,0,0,0,0); if(!hService) { @@ -212,13 +212,13 @@ bool IsServiceRunning() SC_HANDLE hService = OpenService(scm, "NZBGet", SERVICE_QUERY_STATUS); SERVICE_STATUS ServiceStatus; - bool bRunning = false; + bool running = false; if (hService && QueryServiceStatus(hService, &ServiceStatus)) { - bRunning = ServiceStatus.dwCurrentState != SERVICE_STOPPED; + running = ServiceStatus.dwCurrentState != SERVICE_STOPPED; } CloseServiceHandle(scm); - return bRunning; + return running; } diff --git a/daemon/windows/WinConsole.cpp b/daemon/windows/WinConsole.cpp index 0c30f90c..969bf148 100644 --- a/daemon/windows/WinConsole.cpp +++ b/daemon/windows/WinConsole.cpp @@ -68,7 +68,7 @@ extern StatMeter* g_pStatMeter; "name='Microsoft.Windows.Common-Controls' version='6.0.0.0' "\ "processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") -bool bMayStartBrowser = true; +bool mayStartBrowser = true; BOOL WINAPI WinConsole::ConsoleCtrlHandler(DWORD dwCtrlType) { @@ -93,31 +93,31 @@ BOOL WINAPI WinConsole::ConsoleCtrlHandler(DWORD dwCtrlType) WinConsole::WinConsole() { - m_pInitialArguments = NULL; - m_iInitialArgumentCount = 0; - m_pDefaultArguments = NULL; - m_pNidIcon = NULL; - m_bModal = false; - m_bAutostart = false; - m_bTray = true; - m_bConsole = false; - m_bWebUI = true; - m_bAutoParam = false; - m_bDoubleClick = false; + m_initialArguments = NULL; + m_initialArgumentCount = 0; + m_defaultArguments = NULL; + m_nidIcon = NULL; + m_modal = false; + m_autostart = false; + m_tray = true; + m_console = false; + m_webUI = true; + m_autoParam = false; + m_doubleClick = false; m_hTrayWindow = 0; - m_bRunning = false; - m_bRunningService = false; + m_running = false; + m_runningService = false; } WinConsole::~WinConsole() { - if (m_pInitialArguments) + if (m_initialArguments) { - g_szArguments = (char*(*)[])m_pInitialArguments; - g_iArgumentCount = m_iInitialArgumentCount; + g_szArguments = (char*(*)[])m_initialArguments; + g_iArgumentCount = m_initialArgumentCount; } - free(m_pDefaultArguments); - delete m_pNidIcon; + free(m_defaultArguments); + delete m_nidIcon; } void WinConsole::InitAppMode() @@ -127,21 +127,21 @@ void WinConsole::InitAppMode() m_hInstance = (HINSTANCE)GetModuleHandle(0); DWORD dwProcessId; GetWindowThreadProcessId(GetConsoleWindow(), &dwProcessId); - m_bAppMode = false; + m_appMode = false; if (GetCurrentProcessId() == dwProcessId && g_iArgumentCount == 1) { - m_pInitialArguments = (char**)g_szArguments; - m_iInitialArgumentCount = g_iArgumentCount; + m_initialArguments = (char**)g_szArguments; + m_initialArgumentCount = g_iArgumentCount; // make command line to start in server mode - m_pDefaultArguments = (char**)malloc(sizeof(char*) * 3); - m_pDefaultArguments[0] = (*g_szArguments)[0]; - m_pDefaultArguments[1] = "-s"; - m_pDefaultArguments[2] = NULL; - g_szArguments = (char*(*)[])m_pDefaultArguments; + m_defaultArguments = (char**)malloc(sizeof(char*) * 3); + m_defaultArguments[0] = (*g_szArguments)[0]; + m_defaultArguments[1] = "-s"; + m_defaultArguments[2] = NULL; + g_szArguments = (char*(*)[])m_defaultArguments; g_iArgumentCount = 2; - m_bAppMode = true; + m_appMode = true; } else if (GetCurrentProcessId() == dwProcessId && g_iArgumentCount > 1) { @@ -153,23 +153,23 @@ void WinConsole::InitAppMode() } if (!strcmp((*g_szArguments)[i], "-app")) { - m_bAppMode = true; + m_appMode = true; } if (!strcmp((*g_szArguments)[i], "-auto")) { - m_bAutoParam = true; + m_autoParam = true; } } - if (m_bAppMode) + if (m_appMode) { - m_pInitialArguments = (char**)g_szArguments; - m_iInitialArgumentCount = g_iArgumentCount; + m_initialArguments = (char**)g_szArguments; + m_initialArgumentCount = g_iArgumentCount; // remove "-app" from command line - int argc = g_iArgumentCount - 1 - (m_bAutoParam ? 1 : 0); - m_pDefaultArguments = (char**)malloc(sizeof(char*) * (argc + 2)); + int argc = g_iArgumentCount - 1 - (m_autoParam ? 1 : 0); + m_defaultArguments = (char**)malloc(sizeof(char*) * (argc + 2)); int p = 0; for (int i = 0; i < g_iArgumentCount; i++) @@ -177,11 +177,11 @@ void WinConsole::InitAppMode() if (strcmp((*g_szArguments)[i], "-app") && strcmp((*g_szArguments)[i], "-auto")) { - m_pDefaultArguments[p++] = (*g_szArguments)[i]; + m_defaultArguments[p++] = (*g_szArguments)[i]; } } - m_pDefaultArguments[p] = NULL; - g_szArguments = (char*(*)[])m_pDefaultArguments; + m_defaultArguments[p] = NULL; + g_szArguments = (char*(*)[])m_defaultArguments; g_iArgumentCount = p; } } @@ -190,7 +190,7 @@ void WinConsole::InitAppMode() // (not from a dos box window). In that case we hide the console window, // show the tray icon and start in server mode - if (m_bAppMode) + if (m_appMode) { CreateResources(); CheckRunning(); @@ -199,7 +199,7 @@ void WinConsole::InitAppMode() void WinConsole::Run() { - if (!m_bAppMode) + if (!m_appMode) { return; } @@ -211,13 +211,13 @@ void WinConsole::Run() BuildMenu(); - if (m_bWebUI && !m_bAutoParam && bMayStartBrowser) + if (m_webUI && !m_autoParam && mayStartBrowser) { ShowWebUI(); } - bMayStartBrowser = false; + mayStartBrowser = false; - int iCounter = 0; + int counter = 0; while (!IsStopped()) { MSG msg; @@ -229,21 +229,21 @@ void WinConsole::Run() else { usleep(20 * 1000); - iCounter += 20; - if (iCounter >= 200) + counter += 20; + if (counter >= 200) { UpdateTrayIcon(); - iCounter = 0; + counter = 0; } } } - Shell_NotifyIcon(NIM_DELETE, m_pNidIcon); + Shell_NotifyIcon(NIM_DELETE, m_nidIcon); } void WinConsole::Stop() { - if (m_bAppMode) + if (m_appMode) { PostMessage(m_hTrayWindow, WM_QUIT, 0, 0); } @@ -291,23 +291,23 @@ void WinConsole::CreateTrayIcon() m_hTrayWindow = CreateWindowEx(0, className, "NZBGet", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, m_hInstance, NULL); - m_pNidIcon = new NOTIFYICONDATA; - memset(m_pNidIcon, 0, sizeof(NOTIFYICONDATA)); - m_pNidIcon->cbSize = sizeof(NOTIFYICONDATA); - m_pNidIcon->hWnd = m_hTrayWindow; - m_pNidIcon->uID = 100; - m_pNidIcon->uCallbackMessage = UM_TRAYICON; - m_pNidIcon->hIcon = m_hWorkingIcon; - strncpy(m_pNidIcon->szTip, "NZBGet", sizeof(m_pNidIcon->szTip)); - m_pNidIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; + m_nidIcon = new NOTIFYICONDATA; + memset(m_nidIcon, 0, sizeof(NOTIFYICONDATA)); + m_nidIcon->cbSize = sizeof(NOTIFYICONDATA); + m_nidIcon->hWnd = m_hTrayWindow; + m_nidIcon->uID = 100; + m_nidIcon->uCallbackMessage = UM_TRAYICON; + m_nidIcon->hIcon = m_hWorkingIcon; + strncpy(m_nidIcon->szTip, "NZBGet", sizeof(m_nidIcon->szTip)); + m_nidIcon->uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; } -LRESULT CALLBACK WinConsole::TrayWndProcStat(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM lParam) +LRESULT CALLBACK WinConsole::TrayWndProcStat(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM param) { - return g_pWinConsole->TrayWndProc(hwndWin, uMsg, wParam, lParam); + return g_pWinConsole->TrayWndProc(hwndWin, uMsg, wParam, param); } -LRESULT WinConsole::TrayWndProc(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM lParam) +LRESULT WinConsole::TrayWndProc(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM param) { if (uMsg == UM_TASKBARCREATED) { @@ -318,7 +318,7 @@ LRESULT WinConsole::TrayWndProc(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM l switch (uMsg) { case UM_TRAYICON: - if (lParam == WM_LBUTTONUP && !m_bDoubleClick) + if (param == WM_LBUTTONUP && !m_doubleClick) { g_pOptions->SetPauseDownload(!g_pOptions->GetPauseDownload()); g_pOptions->SetPausePostProcess(g_pOptions->GetPauseDownload()); @@ -326,11 +326,11 @@ LRESULT WinConsole::TrayWndProc(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM l g_pOptions->SetResumeTime(0); UpdateTrayIcon(); } - else if (lParam == WM_LBUTTONDBLCLK && m_bDoubleClick) + else if (param == WM_LBUTTONDBLCLK && m_doubleClick) { ShowWebUI(); } - else if (lParam == WM_RBUTTONDOWN) + else if (param == WM_RBUTTONDOWN) { ShowMenu(); } @@ -350,7 +350,7 @@ LRESULT WinConsole::TrayWndProc(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM l return 0; default: - return DefWindowProc(hwndWin, uMsg, wParam, lParam); + return DefWindowProc(hwndWin, uMsg, wParam, param); } } @@ -360,9 +360,9 @@ void WinConsole::ShowMenu() GetCursorPos(&curPoint); SetForegroundWindow(m_hTrayWindow); - UINT iItemID = TrackPopupMenu(m_hMenu, TPM_RETURNCMD | TPM_NONOTIFY, curPoint.x, curPoint.y, 0, m_hTrayWindow, NULL); + UINT itemId = TrackPopupMenu(m_hMenu, TPM_RETURNCMD | TPM_NONOTIFY, curPoint.x, curPoint.y, 0, m_hTrayWindow, NULL); - switch(iItemID) + switch(itemId) { case ID_SHOWWEBUI: ShowWebUI(); @@ -417,7 +417,7 @@ void WinConsole::ShowMenu() break; case ID_TROUBLESHOOTING_RESTART: - bMayStartBrowser = true; + mayStartBrowser = true; Reload(); break; @@ -430,46 +430,46 @@ void WinConsole::ShowMenu() break; } - if (iItemID >= ID_SHOW_DESTDIR + 1000 && iItemID < ID_SHOW_DESTDIR + 2000) + if (itemId >= ID_SHOW_DESTDIR + 1000 && itemId < ID_SHOW_DESTDIR + 2000) { - ShowCategoryDir(iItemID - (ID_SHOW_DESTDIR + 1000)); + ShowCategoryDir(itemId - (ID_SHOW_DESTDIR + 1000)); } } void WinConsole::ShowWebUI() { - const char* szIP = g_pOptions->GetControlIP(); + const char* iP = g_pOptions->GetControlIP(); if (!strcmp(g_pOptions->GetControlIP(), "localhost") || !strcmp(g_pOptions->GetControlIP(), "0.0.0.0")) { - szIP = "127.0.0.1"; + iP = "127.0.0.1"; } - char szURL[1024]; - snprintf(szURL, 1024, "http://%s:%i", szIP, g_pOptions->GetControlPort()); - szURL[1024-1] = '\0'; - ShellExecute(0, "open", szURL, NULL, NULL, SW_SHOWNORMAL); + char url[1024]; + snprintf(url, 1024, "http://%s:%i", iP, g_pOptions->GetControlPort()); + url[1024-1] = '\0'; + ShellExecute(0, "open", url, NULL, NULL, SW_SHOWNORMAL); } -void WinConsole::ShowInExplorer(const char* szFileName) +void WinConsole::ShowInExplorer(const char* fileName) { - char szFileName2[MAX_PATH + 1]; - strncpy(szFileName2, szFileName, MAX_PATH); - szFileName2[MAX_PATH] = '\0'; - Util::NormalizePathSeparators(szFileName2); - if (*szFileName2 && szFileName2[strlen(szFileName2) - 1] == PATH_SEPARATOR) szFileName2[strlen(szFileName2) - 1] = '\0'; // trim slash + char fileName2[MAX_PATH + 1]; + strncpy(fileName2, fileName, MAX_PATH); + fileName2[MAX_PATH] = '\0'; + Util::NormalizePathSeparators(fileName2); + if (*fileName2 && fileName2[strlen(fileName2) - 1] == PATH_SEPARATOR) fileName2[strlen(fileName2) - 1] = '\0'; // trim slash - if (!Util::FileExists(szFileName2) && !Util::DirectoryExists(szFileName2)) + if (!Util::FileExists(fileName2) && !Util::DirectoryExists(fileName2)) { - char szMessage[400]; - snprintf(szMessage, 400, "Directory or file %s doesn't exist (yet).", szFileName2); - szMessage[400-1] = '\0'; - MessageBox(m_hTrayWindow, szMessage, "Information", MB_ICONINFORMATION); + char message[400]; + snprintf(message, 400, "Directory or file %s doesn't exist (yet).", fileName2); + message[400-1] = '\0'; + MessageBox(m_hTrayWindow, message, "Information", MB_ICONINFORMATION); return; } WCHAR wszFileName2[MAX_PATH + 1]; - MultiByteToWideChar(0, 0, szFileName2, strlen(szFileName2) + 1, wszFileName2, MAX_PATH); + MultiByteToWideChar(0, 0, fileName2, strlen(fileName2) + 1, wszFileName2, MAX_PATH); CoInitialize(NULL); LPITEMIDLIST pidl; HRESULT H = SHParseDisplayName(wszFileName2, NULL, &pidl, 0, NULL); @@ -478,31 +478,31 @@ void WinConsole::ShowInExplorer(const char* szFileName) void WinConsole::ShowAboutBox() { - if (m_bModal) + if (m_modal) { return; } - m_bModal = true; + m_modal = true; DialogBox(m_hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), m_hTrayWindow, AboutDialogProcStat); - m_bModal = false; + m_modal = false; } -BOOL CALLBACK WinConsole::AboutDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL CALLBACK WinConsole::AboutDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { - return g_pWinConsole->AboutDialogProc(hwndDlg, uMsg, wParam, lParam); + return g_pWinConsole->AboutDialogProc(hwndDlg, uMsg, wParam, param); } -BOOL WinConsole::AboutDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL WinConsole::AboutDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { switch(uMsg) { case WM_INITDIALOG: SendDlgItemMessage(hwndDlg, IDC_ABOUT_NAME, WM_SETFONT, (WPARAM)m_hNameFont, 0); - char szVersion[100]; - snprintf(szVersion, 100, "Version %s", Util::VersionRevision()); - SetDlgItemText(hwndDlg, IDC_ABOUT_VERSION, szVersion); + char version[100]; + snprintf(version, 100, "Version %s", Util::VersionRevision()); + SetDlgItemText(hwndDlg, IDC_ABOUT_VERSION, version); SendDlgItemMessage(hwndDlg, IDC_ABOUT_ICON, STM_SETICON, (WPARAM)m_hAboutIcon, 0); @@ -531,8 +531,8 @@ BOOL WinConsole::AboutDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM return TRUE; case WM_CTLCOLORSTATIC: - if ((HWND)lParam == GetDlgItem(hwndDlg, IDC_ABOUT_HOMEPAGE) || - (HWND)lParam == GetDlgItem(hwndDlg, IDC_ABOUT_GPL)) + if ((HWND)param == GetDlgItem(hwndDlg, IDC_ABOUT_HOMEPAGE) || + (HWND)param == GetDlgItem(hwndDlg, IDC_ABOUT_GPL)) { SetTextColor((HDC)wParam, RGB(0, 0, 255)); SetBkColor((HDC)wParam, GetSysColor(COLOR_BTNFACE)); @@ -557,34 +557,34 @@ BOOL WinConsole::AboutDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM void WinConsole::ShowPrefsDialog() { - if (m_bModal) + if (m_modal) { return; } - m_bModal = true; + m_modal = true; DialogBox(m_hInstance, MAKEINTRESOURCE(IDD_PREFDIALOG), m_hTrayWindow, PrefsDialogProcStat); - m_bModal = false; + m_modal = false; } -BOOL CALLBACK WinConsole::PrefsDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL CALLBACK WinConsole::PrefsDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { - return g_pWinConsole->PrefsDialogProc(hwndDlg, uMsg, wParam, lParam); + return g_pWinConsole->PrefsDialogProc(hwndDlg, uMsg, wParam, param); } -BOOL WinConsole::PrefsDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL WinConsole::PrefsDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { switch(uMsg) { case WM_INITDIALOG: LoadPrefs(); - SendDlgItemMessage(hwndDlg, IDC_PREF_AUTOSTART, BM_SETCHECK, m_bAutostart, 0); - SendDlgItemMessage(hwndDlg, IDC_PREF_TRAY, BM_SETCHECK, m_bTray, 0); - SendDlgItemMessage(hwndDlg, IDC_PREF_CONSOLE, BM_SETCHECK, m_bConsole, 0); - SendDlgItemMessage(hwndDlg, IDC_PREF_WEBUI, BM_SETCHECK, m_bWebUI, 0); - SendDlgItemMessage(hwndDlg, IDC_PREF_TRAYPAUSE, BM_SETCHECK, !m_bDoubleClick, 0); - SendDlgItemMessage(hwndDlg, IDC_PREF_TRAYWEBUI, BM_SETCHECK, m_bDoubleClick, 0); + SendDlgItemMessage(hwndDlg, IDC_PREF_AUTOSTART, BM_SETCHECK, m_autostart, 0); + SendDlgItemMessage(hwndDlg, IDC_PREF_TRAY, BM_SETCHECK, m_tray, 0); + SendDlgItemMessage(hwndDlg, IDC_PREF_CONSOLE, BM_SETCHECK, m_console, 0); + SendDlgItemMessage(hwndDlg, IDC_PREF_WEBUI, BM_SETCHECK, m_webUI, 0); + SendDlgItemMessage(hwndDlg, IDC_PREF_TRAYPAUSE, BM_SETCHECK, !m_doubleClick, 0); + SendDlgItemMessage(hwndDlg, IDC_PREF_TRAYWEBUI, BM_SETCHECK, m_doubleClick, 0); return FALSE; @@ -595,14 +595,14 @@ BOOL WinConsole::PrefsDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM case WM_COMMAND: if (LOWORD(wParam) == IDOK) { - m_bAutostart = SendDlgItemMessage(hwndDlg, IDC_PREF_AUTOSTART, BM_GETCHECK, 0, 0) == BST_CHECKED; - m_bTray = SendDlgItemMessage(hwndDlg, IDC_PREF_TRAY, BM_GETCHECK, 0, 0) == BST_CHECKED; - m_bConsole = SendDlgItemMessage(hwndDlg, IDC_PREF_CONSOLE, BM_GETCHECK, 0, 0) == BST_CHECKED; - m_bWebUI = SendDlgItemMessage(hwndDlg, IDC_PREF_WEBUI, BM_GETCHECK, 0, 0) == BST_CHECKED; - m_bDoubleClick = SendDlgItemMessage(hwndDlg, IDC_PREF_TRAYWEBUI, BM_GETCHECK, 0, 0) == BST_CHECKED; + m_autostart = SendDlgItemMessage(hwndDlg, IDC_PREF_AUTOSTART, BM_GETCHECK, 0, 0) == BST_CHECKED; + m_tray = SendDlgItemMessage(hwndDlg, IDC_PREF_TRAY, BM_GETCHECK, 0, 0) == BST_CHECKED; + m_console = SendDlgItemMessage(hwndDlg, IDC_PREF_CONSOLE, BM_GETCHECK, 0, 0) == BST_CHECKED; + m_webUI = SendDlgItemMessage(hwndDlg, IDC_PREF_WEBUI, BM_GETCHECK, 0, 0) == BST_CHECKED; + m_doubleClick = SendDlgItemMessage(hwndDlg, IDC_PREF_TRAYWEBUI, BM_GETCHECK, 0, 0) == BST_CHECKED; SavePrefs(); - if (!m_bRunning) + if (!m_running) { ApplyPrefs(); } @@ -626,30 +626,30 @@ void WinConsole::SavePrefs() HKEY hKey; RegCreateKey(HKEY_CURRENT_USER, "Software\\NZBGet", &hKey); - val = m_bTray; + val = m_tray; RegSetValueEx(hKey, "ShowTrayIcon", 0, REG_DWORD, (BYTE*)&val, sizeof(val)); - val = m_bConsole; + val = m_console; RegSetValueEx(hKey, "ShowConsole", 0, REG_DWORD, (BYTE*)&val, sizeof(val)); - val = m_bWebUI; + val = m_webUI; RegSetValueEx(hKey, "ShowWebUI", 0, REG_DWORD, (BYTE*)&val, sizeof(val)); - val = m_bDoubleClick; + val = m_doubleClick; RegSetValueEx(hKey, "TrayDoubleClick", 0, REG_DWORD, (BYTE*)&val, sizeof(val)); RegCloseKey(hKey); // Autostart-setting RegCreateKey(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", &hKey); - if (m_bAutostart) + if (m_autostart) { - char szFilename[MAX_PATH + 1]; - GetModuleFileName(NULL, szFilename, sizeof(szFilename)); - char szStartCommand[1024]; - snprintf(szStartCommand, sizeof(szStartCommand), "\"%s\" -s -app -auto", szFilename); - szStartCommand[1024-1] = '\0'; - RegSetValueEx(hKey, "NZBGet", 0, REG_SZ, (BYTE*)szStartCommand, strlen(szStartCommand) + 1); + char filename[MAX_PATH + 1]; + GetModuleFileName(NULL, filename, sizeof(filename)); + char startCommand[1024]; + snprintf(startCommand, sizeof(startCommand), "\"%s\" -s -app -auto", filename); + startCommand[1024-1] = '\0'; + RegSetValueEx(hKey, "NZBGet", 0, REG_SZ, (BYTE*)startCommand, strlen(startCommand) + 1); } else { @@ -669,22 +669,22 @@ void WinConsole::LoadPrefs() { if (RegQueryValueEx(hKey, "ShowTrayIcon", 0, &typ, (LPBYTE)&val, &cval) == ERROR_SUCCESS) { - m_bTray = val; + m_tray = val; } if (RegQueryValueEx(hKey, "ShowConsole", 0, &typ, (LPBYTE)&val, &cval) == ERROR_SUCCESS) { - m_bConsole = val; + m_console = val; } if (RegQueryValueEx(hKey, "ShowWebUI", 0, &typ, (LPBYTE)&val, &cval) == ERROR_SUCCESS) { - m_bWebUI = val; + m_webUI = val; } if (RegQueryValueEx(hKey, "TrayDoubleClick", 0, &typ, (LPBYTE)&val, &cval) == ERROR_SUCCESS) { - m_bDoubleClick = val; + m_doubleClick = val; } RegCloseKey(hKey); @@ -693,19 +693,19 @@ void WinConsole::LoadPrefs() // Autostart-setting if (RegOpenKey(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", &hKey) == ERROR_SUCCESS) { - m_bAutostart = RegQueryValueEx(hKey, "NZBGet", 0, &typ, NULL, NULL) == ERROR_SUCCESS; + m_autostart = RegQueryValueEx(hKey, "NZBGet", 0, &typ, NULL, NULL) == ERROR_SUCCESS; RegCloseKey(hKey); } } void WinConsole::ApplyPrefs() { - ShowWindow(GetConsoleWindow(), m_bConsole ? SW_SHOW : SW_HIDE); - if (m_bTray) + ShowWindow(GetConsoleWindow(), m_console ? SW_SHOW : SW_HIDE); + if (m_tray) { UpdateTrayIcon(); } - Shell_NotifyIcon(m_bTray ? NIM_ADD : NIM_DELETE, m_pNidIcon); + Shell_NotifyIcon(m_tray ? NIM_ADD : NIM_DELETE, m_nidIcon); } void WinConsole::CheckRunning() @@ -719,7 +719,7 @@ void WinConsole::CheckRunning() if (IsServiceRunning()) { - m_bRunningService = true; + m_runningService = true; ShowRunningDialog(); ExitProcess(1); } @@ -727,13 +727,13 @@ void WinConsole::CheckRunning() void WinConsole::ShowRunningDialog() { - ShowWindow(GetConsoleWindow(), m_bConsole ? SW_SHOW : SW_HIDE); + ShowWindow(GetConsoleWindow(), m_console ? SW_SHOW : SW_HIDE); HWND hTrayWindow = FindWindow("NZBGet tray window", NULL); - m_bRunning = true; + m_running = true; - int iResult = DialogBox(m_hInstance, MAKEINTRESOURCE(IDD_RUNNINGDIALOG), m_hTrayWindow, RunningDialogProcStat); + int result = DialogBox(m_hInstance, MAKEINTRESOURCE(IDD_RUNNINGDIALOG), m_hTrayWindow, RunningDialogProcStat); - switch (iResult) + switch (result) { case IDC_RUNNING_WEBUI: PostMessage(hTrayWindow, UM_SHOWWEBUI, 0, 0); @@ -750,12 +750,12 @@ void WinConsole::ShowRunningDialog() } } -BOOL CALLBACK WinConsole::RunningDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL CALLBACK WinConsole::RunningDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { - return g_pWinConsole->RunningDialogProc(hwndDlg, uMsg, wParam, lParam); + return g_pWinConsole->RunningDialogProc(hwndDlg, uMsg, wParam, param); } -BOOL WinConsole::RunningDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL WinConsole::RunningDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { switch(uMsg) { @@ -763,7 +763,7 @@ BOOL WinConsole::RunningDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARA SendDlgItemMessage(hwndDlg, IDC_RUNNING_ICON, STM_SETICON, (WPARAM)m_hRunningIcon, 0); SendDlgItemMessage(hwndDlg, IDC_RUNNING_TITLE, WM_SETFONT, (WPARAM)m_hTitleFont, 0); - if (m_bRunningService) + if (m_runningService) { SetDlgItemText(hwndDlg, IDC_RUNNING_TEXT, "Another instance of NZBGet is running as Windows Service. Please use Management Console to control the service."); ShowWindow(GetDlgItem(hwndDlg, IDC_RUNNING_WEBUI), SW_HIDE); @@ -789,83 +789,83 @@ BOOL WinConsole::RunningDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARA void WinConsole::UpdateTrayIcon() { - if (!m_bTray) + if (!m_tray) { return; } - HICON hOldIcon = m_pNidIcon->hIcon; + HICON hOldIcon = m_nidIcon->hIcon; - char szOldTip[200]; - strncpy(szOldTip, m_pNidIcon->szTip, sizeof(m_pNidIcon->szTip)); - szOldTip[200-1] = '\0'; + char oldTip[200]; + strncpy(oldTip, m_nidIcon->szTip, sizeof(m_nidIcon->szTip)); + oldTip[200-1] = '\0'; if (g_pOptions->GetPauseDownload()) { - m_pNidIcon->hIcon = m_hPausedIcon; - strncpy(m_pNidIcon->szTip, "NZBGet - paused", sizeof(m_pNidIcon->szTip)); + m_nidIcon->hIcon = m_hPausedIcon; + strncpy(m_nidIcon->szTip, "NZBGet - paused", sizeof(m_nidIcon->szTip)); } else if (!g_pStatMeter->GetStandBy()) { - m_pNidIcon->hIcon = m_hWorkingIcon; - char szSpeed[100]; - Util::FormatSpeed(szSpeed, sizeof(szSpeed), g_pStatMeter->CalcCurrentDownloadSpeed()); - char szTip[200]; - snprintf(szTip, sizeof(szTip), "NZBGet - downloading at %s", szSpeed); - szTip[200-1] = '\0'; - strncpy(m_pNidIcon->szTip, szTip, sizeof(m_pNidIcon->szTip)); + m_nidIcon->hIcon = m_hWorkingIcon; + char speed[100]; + Util::FormatSpeed(speed, sizeof(speed), g_pStatMeter->CalcCurrentDownloadSpeed()); + char tip[200]; + snprintf(tip, sizeof(tip), "NZBGet - downloading at %s", speed); + tip[200-1] = '\0'; + strncpy(m_nidIcon->szTip, tip, sizeof(m_nidIcon->szTip)); } else { - DownloadQueue *pDownloadQueue = DownloadQueue::Lock(); - int iPostJobCount = 0; - int iUrlCount = 0; - for (NZBList::iterator it = pDownloadQueue->GetQueue()->begin(); it != pDownloadQueue->GetQueue()->end(); it++) + DownloadQueue *downloadQueue = DownloadQueue::Lock(); + int postJobCount = 0; + int urlCount = 0; + for (NZBList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++) { - NZBInfo* pNZBInfo = *it; - iPostJobCount += pNZBInfo->GetPostInfo() ? 1 : 0; - iUrlCount += pNZBInfo->GetKind() == NZBInfo::nkUrl ? 1 : 0; + NZBInfo* nzbInfo = *it; + postJobCount += nzbInfo->GetPostInfo() ? 1 : 0; + urlCount += nzbInfo->GetKind() == NZBInfo::nkUrl ? 1 : 0; } DownloadQueue::Unlock(); - if (iPostJobCount > 0) + if (postJobCount > 0) { - m_pNidIcon->hIcon = m_hWorkingIcon; - strncpy(m_pNidIcon->szTip, "NZBGet - post-processing", sizeof(m_pNidIcon->szTip)); + m_nidIcon->hIcon = m_hWorkingIcon; + strncpy(m_nidIcon->szTip, "NZBGet - post-processing", sizeof(m_nidIcon->szTip)); } - else if (iUrlCount > 0) + else if (urlCount > 0) { - m_pNidIcon->hIcon = m_hWorkingIcon; - strncpy(m_pNidIcon->szTip, "NZBGet - fetching URLs", sizeof(m_pNidIcon->szTip)); + m_nidIcon->hIcon = m_hWorkingIcon; + strncpy(m_nidIcon->szTip, "NZBGet - fetching URLs", sizeof(m_nidIcon->szTip)); } else if (g_pFeedCoordinator->HasActiveDownloads()) { - m_pNidIcon->hIcon = m_hWorkingIcon; - strncpy(m_pNidIcon->szTip, "NZBGet - fetching feeds", sizeof(m_pNidIcon->szTip)); + m_nidIcon->hIcon = m_hWorkingIcon; + strncpy(m_nidIcon->szTip, "NZBGet - fetching feeds", sizeof(m_nidIcon->szTip)); } else { - m_pNidIcon->hIcon = m_hIdleIcon; - strncpy(m_pNidIcon->szTip, "NZBGet - idle", sizeof(m_pNidIcon->szTip)); + m_nidIcon->hIcon = m_hIdleIcon; + strncpy(m_nidIcon->szTip, "NZBGet - idle", sizeof(m_nidIcon->szTip)); } } - if (m_pNidIcon->hIcon != hOldIcon || strcmp(szOldTip, m_pNidIcon->szTip)) + if (m_nidIcon->hIcon != hOldIcon || strcmp(oldTip, m_nidIcon->szTip)) { - Shell_NotifyIcon(NIM_MODIFY, m_pNidIcon); + Shell_NotifyIcon(NIM_MODIFY, m_nidIcon); } } void WinConsole::BuildMenu() { - int iIndex = 0; - for (Options::Categories::iterator it = g_pOptions->GetCategories()->begin(); it != g_pOptions->GetCategories()->end(); it++, iIndex++) + int index = 0; + for (Options::Categories::iterator it = g_pOptions->GetCategories()->begin(); it != g_pOptions->GetCategories()->end(); it++, index++) { - Options::Category* pCategory = *it; + Options::Category* category = *it; - char szCaption[250]; - snprintf(szCaption, 250, "Category %i: %s", iIndex + 1, pCategory->GetName()); - szCaption[250 - 1] = '\0'; + char caption[250]; + snprintf(caption, 250, "Category %i: %s", index + 1, category->GetName()); + caption[250 - 1] = '\0'; MENUITEMINFO item; ZeroMemory(&item, sizeof(MENUITEMINFO)); @@ -873,9 +873,9 @@ void WinConsole::BuildMenu() item.fMask = MIIM_ID | MIIM_STRING; item.fType = MFT_STRING; item.fState = MFS_DEFAULT; - item.wID = ID_SHOW_DESTDIR + 1000 + iIndex; - item.dwTypeData = szCaption; - InsertMenuItem(GetSubMenu(m_hMenu, 1), 2 + iIndex, TRUE, &item); + item.wID = ID_SHOW_DESTDIR + 1000 + index; + item.dwTypeData = caption; + InsertMenuItem(GetSubMenu(m_hMenu, 1), 2 + index, TRUE, &item); } /* @@ -888,37 +888,37 @@ BOOL DeleteMenu( */ } -void WinConsole::ShowCategoryDir(int iCatIndex) +void WinConsole::ShowCategoryDir(int catIndex) { - Options::Category* pCategory = g_pOptions->GetCategories()->at(iCatIndex); + Options::Category* category = g_pOptions->GetCategories()->at(catIndex); - char szDestDir[1024]; + char destDir[1024]; - if (!Util::EmptyStr(pCategory->GetDestDir())) + if (!Util::EmptyStr(category->GetDestDir())) { - snprintf(szDestDir, 1024, "%s", pCategory->GetDestDir()); - szDestDir[1024-1] = '\0'; + snprintf(destDir, 1024, "%s", category->GetDestDir()); + destDir[1024-1] = '\0'; } else { - char szCategoryDir[1024]; - strncpy(szCategoryDir, pCategory->GetName(), 1024); - szCategoryDir[1024 - 1] = '\0'; - Util::MakeValidFilename(szCategoryDir, '_', true); + char categoryDir[1024]; + strncpy(categoryDir, category->GetName(), 1024); + categoryDir[1024 - 1] = '\0'; + Util::MakeValidFilename(categoryDir, '_', true); - snprintf(szDestDir, 1024, "%s%s", g_pOptions->GetDestDir(), szCategoryDir); - szDestDir[1024-1] = '\0'; + snprintf(destDir, 1024, "%s%s", g_pOptions->GetDestDir(), categoryDir); + destDir[1024-1] = '\0'; } - ShowInExplorer(szDestDir); + ShowInExplorer(destDir); } void WinConsole::OpenConfigFileInTextEdit() { - char szParam[MAX_PATH + 3]; - snprintf(szParam, sizeof(szParam), "\"%s\"", g_pOptions->GetConfigFilename()); - szParam[sizeof(szParam)-1] = '\0'; - ShellExecute(0, "open", "notepad.exe", szParam, NULL, SW_SHOWNORMAL); + char param[MAX_PATH + 3]; + snprintf(param, sizeof(param), "\"%s\"", g_pOptions->GetConfigFilename()); + param[sizeof(param)-1] = '\0'; + ShellExecute(0, "open", "notepad.exe", param, NULL, SW_SHOWNORMAL); } void WinConsole::SetupFirstStart() @@ -931,84 +931,84 @@ void WinConsole::SetupConfigFile() { // create new config-file from config template - char szFilename[MAX_PATH + 30]; + char filename[MAX_PATH + 30]; - char szCommonAppDataPath[MAX_PATH]; - SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szCommonAppDataPath); + char commonAppDataPath[MAX_PATH]; + SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, commonAppDataPath); - snprintf(szFilename, sizeof(szFilename), "%s\\NZBGet\\nzbget.conf", szCommonAppDataPath); - szFilename[sizeof(szFilename)-1] = '\0'; + snprintf(filename, sizeof(filename), "%s\\NZBGet\\nzbget.conf", commonAppDataPath); + filename[sizeof(filename)-1] = '\0'; - char szAppDataPath[MAX_PATH + 1]; - snprintf(szAppDataPath, sizeof(szAppDataPath), "%s\\NZBGet", szCommonAppDataPath); - szAppDataPath[sizeof(szAppDataPath)-1] = '\0'; - Util::CreateDirectory(szAppDataPath); + char appDataPath[MAX_PATH + 1]; + snprintf(appDataPath, sizeof(appDataPath), "%s\\NZBGet", commonAppDataPath); + appDataPath[sizeof(appDataPath)-1] = '\0'; + Util::CreateDirectory(appDataPath); - char szConfTemplateFilename[MAX_PATH + 30]; - snprintf(szConfTemplateFilename, sizeof(szConfTemplateFilename), "%s\\nzbget.conf.template", g_pOptions->GetAppDir()); - szConfTemplateFilename[sizeof(szConfTemplateFilename)-1] = '\0'; + char confTemplateFilename[MAX_PATH + 30]; + snprintf(confTemplateFilename, sizeof(confTemplateFilename), "%s\\nzbget.conf.template", g_pOptions->GetAppDir()); + confTemplateFilename[sizeof(confTemplateFilename)-1] = '\0'; - CopyFile(szConfTemplateFilename, szFilename, FALSE); + CopyFile(confTemplateFilename, filename, FALSE); // set MainDir in the config-file - int iSize = 0; - char* szConfig = NULL; - if (Util::LoadFileIntoBuffer(szFilename, &szConfig, &iSize)) + int size = 0; + char* config = NULL; + if (Util::LoadFileIntoBuffer(filename, &config, &size)) { const char* SIGNATURE = "MainDir=${AppDir}\\downloads"; - char* p = strstr(szConfig, SIGNATURE); + char* p = strstr(config, SIGNATURE); if (p) { - FILE* outfile = fopen(szFilename, FOPEN_WBP); + FILE* outfile = fopen(filename, FOPEN_WBP); if (outfile) { - fwrite(szConfig, 1, p - szConfig, outfile); + fwrite(config, 1, p - config, outfile); fwrite("MainDir=", 1, 8, outfile); - fwrite(szAppDataPath, 1, strlen(szAppDataPath), outfile); + fwrite(appDataPath, 1, strlen(appDataPath), outfile); - fwrite(p + strlen(SIGNATURE), 1, iSize - (p + strlen(SIGNATURE) - szConfig) - 1, outfile); + fwrite(p + strlen(SIGNATURE), 1, size - (p + strlen(SIGNATURE) - config) - 1, outfile); fclose(outfile); } } - free(szConfig); + free(config); } // create default destination directory (which is not created on start automatically) - snprintf(szFilename, sizeof(szFilename), "%s\\NZBGet\\complete", szCommonAppDataPath); - szFilename[sizeof(szFilename)-1] = '\0'; - Util::CreateDirectory(szFilename); + snprintf(filename, sizeof(filename), "%s\\NZBGet\\complete", commonAppDataPath); + filename[sizeof(filename)-1] = '\0'; + Util::CreateDirectory(filename); } void WinConsole::SetupScripts() { // copy default scripts - char szAppDataPath[MAX_PATH]; - SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szAppDataPath); + char appDataPath[MAX_PATH]; + SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, appDataPath); - char szDestDir[MAX_PATH + 1]; - snprintf(szDestDir, sizeof(szDestDir), "%s\\NZBGet\\scripts", szAppDataPath); - szDestDir[sizeof(szDestDir)-1] = '\0'; - Util::CreateDirectory(szDestDir); + char destDir[MAX_PATH + 1]; + snprintf(destDir, sizeof(destDir), "%s\\NZBGet\\scripts", appDataPath); + destDir[sizeof(destDir)-1] = '\0'; + Util::CreateDirectory(destDir); - char szSrcDir[MAX_PATH + 30]; - snprintf(szSrcDir, sizeof(szSrcDir), "%s\\scripts", g_pOptions->GetAppDir()); - szSrcDir[sizeof(szSrcDir)-1] = '\0'; + char srcDir[MAX_PATH + 30]; + snprintf(srcDir, sizeof(srcDir), "%s\\scripts", g_pOptions->GetAppDir()); + srcDir[sizeof(srcDir)-1] = '\0'; - DirBrowser dir(szSrcDir); - while (const char* szFilename = dir.Next()) + DirBrowser dir(srcDir); + while (const char* filename = dir.Next()) { - if (strcmp(szFilename, ".") && strcmp(szFilename, "..")) + if (strcmp(filename, ".") && strcmp(filename, "..")) { - char szSrcFullFilename[1024]; - snprintf(szSrcFullFilename, 1024, "%s\\%s", szSrcDir, szFilename); - szSrcFullFilename[1024-1] = '\0'; + char srcFullFilename[1024]; + snprintf(srcFullFilename, 1024, "%s\\%s", srcDir, filename); + srcFullFilename[1024-1] = '\0'; - char szDstFullFilename[1024]; - snprintf(szDstFullFilename, 1024, "%s\\%s", szDestDir, szFilename); - szDstFullFilename[1024-1] = '\0'; + char dstFullFilename[1024]; + snprintf(dstFullFilename, 1024, "%s\\%s", destDir, filename); + dstFullFilename[1024-1] = '\0'; - CopyFile(szSrcFullFilename, szDstFullFilename, FALSE); + CopyFile(srcFullFilename, dstFullFilename, FALSE); } } } @@ -1016,11 +1016,11 @@ void WinConsole::SetupScripts() void WinConsole::ShowFactoryResetDialog() { HWND hTrayWindow = FindWindow("NZBGet tray window", NULL); - m_bRunning = true; + m_running = true; - int iResult = DialogBox(m_hInstance, MAKEINTRESOURCE(IDD_FACTORYRESETDIALOG), m_hTrayWindow, FactoryResetDialogProcStat); + int result = DialogBox(m_hInstance, MAKEINTRESOURCE(IDD_FACTORYRESETDIALOG), m_hTrayWindow, FactoryResetDialogProcStat); - switch (iResult) + switch (result) { case IDC_FACTORYRESET_RESET: ResetFactoryDefaults(); @@ -1028,12 +1028,12 @@ void WinConsole::ShowFactoryResetDialog() } } -BOOL CALLBACK WinConsole::FactoryResetDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL CALLBACK WinConsole::FactoryResetDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { - return g_pWinConsole->FactoryResetDialogProc(hwndDlg, uMsg, wParam, lParam); + return g_pWinConsole->FactoryResetDialogProc(hwndDlg, uMsg, wParam, param); } -BOOL WinConsole::FactoryResetDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +BOOL WinConsole::FactoryResetDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param) { switch(uMsg) { @@ -1057,85 +1057,85 @@ BOOL WinConsole::FactoryResetDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, void WinConsole::ResetFactoryDefaults() { - char szPath[MAX_PATH + 100]; - char szMessage[1024]; - char szErrBuf[200]; + char path[MAX_PATH + 100]; + char message[1024]; + char errBuf[200]; g_pOptions->SetPauseDownload(true); g_pOptions->SetPausePostProcess(true); - char szCommonAppDataPath[MAX_PATH]; - SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szCommonAppDataPath); + char commonAppDataPath[MAX_PATH]; + SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, commonAppDataPath); // delete default directories const char* DefDirs[] = {"nzb", "tmp", "queue", "scripts"}; for (int i=0; i < 4; i++) { - snprintf(szPath, sizeof(szPath), "%s\\NZBGet\\%s", szCommonAppDataPath, DefDirs[i]); - szPath[sizeof(szPath)-1] = '\0'; + snprintf(path, sizeof(path), "%s\\NZBGet\\%s", commonAppDataPath, DefDirs[i]); + path[sizeof(path)-1] = '\0'; // try to delete the directory - int iRetry = 10; - while (iRetry > 0 && Util::DirectoryExists(szPath) && - !Util::DeleteDirectoryWithContent(szPath, szErrBuf, sizeof(szErrBuf))) + int retry = 10; + while (retry > 0 && Util::DirectoryExists(path) && + !Util::DeleteDirectoryWithContent(path, errBuf, sizeof(errBuf))) { usleep(200 * 1000); - iRetry--; + retry--; } - if (Util::DirectoryExists(szPath)) + if (Util::DirectoryExists(path)) { - snprintf(szMessage, 1024, "Could not delete directory %s:\n%s.\nPlease delete the directory manually and try again.", szPath, szErrBuf); - szMessage[1024-1] = '\0'; - MessageBox(m_hTrayWindow, szMessage, "NZBGet", MB_ICONERROR); + snprintf(message, 1024, "Could not delete directory %s:\n%s.\nPlease delete the directory manually and try again.", path, errBuf); + message[1024-1] = '\0'; + MessageBox(m_hTrayWindow, message, "NZBGet", MB_ICONERROR); return; } } // delete old config file in the program's directory - snprintf(szPath, sizeof(szPath), "%s\\nzbget.conf", g_pOptions->GetAppDir()); + snprintf(path, sizeof(path), "%s\\nzbget.conf", g_pOptions->GetAppDir()); - remove(szPath); - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf)); + remove(path); + Util::GetLastErrorMessage(errBuf, sizeof(errBuf)); - if (Util::FileExists(szPath)) + if (Util::FileExists(path)) { - snprintf(szMessage, 1024, "Could not delete file %s:\n%s.\nPlease delete the file manually and try again.", szPath, szErrBuf); - szMessage[1024-1] = '\0'; - MessageBox(m_hTrayWindow, szMessage, "NZBGet", MB_ICONERROR); + snprintf(message, 1024, "Could not delete file %s:\n%s.\nPlease delete the file manually and try again.", path, errBuf); + message[1024-1] = '\0'; + MessageBox(m_hTrayWindow, message, "NZBGet", MB_ICONERROR); return; } // delete config file in default directory - snprintf(szPath, sizeof(szPath), "%s\\NZBGet\\nzbget.conf", szCommonAppDataPath); - szPath[sizeof(szPath)-1] = '\0'; + snprintf(path, sizeof(path), "%s\\NZBGet\\nzbget.conf", commonAppDataPath); + path[sizeof(path)-1] = '\0'; - remove(szPath); - Util::GetLastErrorMessage(szErrBuf, sizeof(szErrBuf)); + remove(path); + Util::GetLastErrorMessage(errBuf, sizeof(errBuf)); - if (Util::FileExists(szPath)) + if (Util::FileExists(path)) { - snprintf(szMessage, 1024, "Could not delete file %s:\n%s.\nPlease delete the file manually and try again.", szPath, szErrBuf); - szMessage[1024-1] = '\0'; - MessageBox(m_hTrayWindow, szMessage, "NZBGet", MB_ICONERROR); + snprintf(message, 1024, "Could not delete file %s:\n%s.\nPlease delete the file manually and try again.", path, errBuf); + message[1024-1] = '\0'; + MessageBox(m_hTrayWindow, message, "NZBGet", MB_ICONERROR); return; } // delete log files in default directory - snprintf(szPath, sizeof(szPath), "%s\\NZBGet", szCommonAppDataPath); - szPath[sizeof(szPath)-1] = '\0'; + snprintf(path, sizeof(path), "%s\\NZBGet", commonAppDataPath); + path[sizeof(path)-1] = '\0'; - DirBrowser dir(szPath); - while (const char* szFilename = dir.Next()) + DirBrowser dir(path); + while (const char* filename = dir.Next()) { - if (Util::MatchFileExt(szFilename, ".log", ",")) + if (Util::MatchFileExt(filename, ".log", ",")) { - char szFullFilename[1024]; - snprintf(szFullFilename, 1024, "%s%c%s", szPath, PATH_SEPARATOR, szFilename); - szFullFilename[1024-1] = '\0'; + char fullFilename[1024]; + snprintf(fullFilename, 1024, "%s%c%s", path, PATH_SEPARATOR, filename); + fullFilename[1024-1] = '\0'; - remove(szFullFilename); + remove(fullFilename); // ignore errors } @@ -1144,6 +1144,6 @@ void WinConsole::ResetFactoryDefaults() MessageBox(m_hTrayWindow, "The program has been reset to factory defaults.", "NZBGet", MB_ICONINFORMATION); - bMayStartBrowser = true; + mayStartBrowser = true; Reload(); } diff --git a/daemon/windows/WinConsole.h b/daemon/windows/WinConsole.h index d9bb2a63..d950a136 100644 --- a/daemon/windows/WinConsole.h +++ b/daemon/windows/WinConsole.h @@ -31,16 +31,16 @@ class WinConsole : public Thread { private: - bool m_bAppMode; - char** m_pDefaultArguments; - char** m_pInitialArguments; - int m_iInitialArgumentCount; + bool m_appMode; + char** m_defaultArguments; + char** m_initialArguments; + int m_initialArgumentCount; HWND m_hTrayWindow; - NOTIFYICONDATA* m_pNidIcon; + NOTIFYICONDATA* m_nidIcon; UINT UM_TASKBARCREATED; HMENU m_hMenu; HINSTANCE m_hInstance; - bool m_bModal; + bool m_modal; HFONT m_hLinkFont; HFONT m_hNameFont; HFONT m_hTitleFont; @@ -50,20 +50,20 @@ private: HICON m_hIdleIcon; HICON m_hWorkingIcon; HICON m_hPausedIcon; - bool m_bAutostart; - bool m_bTray; - bool m_bConsole; - bool m_bWebUI; - bool m_bAutoParam; - bool m_bRunning; - bool m_bRunningService; - bool m_bDoubleClick; + bool m_autostart; + bool m_tray; + bool m_console; + bool m_webUI; + bool m_autoParam; + bool m_running; + bool m_runningService; + bool m_doubleClick; void CreateResources(); void CreateTrayIcon(); void ShowWebUI(); void ShowMenu(); - void ShowInExplorer(const char* szFileName); + void ShowInExplorer(const char* fileName); void ShowAboutBox(); void OpenConfigFileInTextEdit(); void ShowPrefsDialog(); @@ -74,23 +74,23 @@ private: void CheckRunning(); void UpdateTrayIcon(); void BuildMenu(); - void ShowCategoryDir(int iCatIndex); + void ShowCategoryDir(int catIndex); void SetupConfigFile(); void SetupScripts(); void ShowFactoryResetDialog(); void ResetFactoryDefaults(); static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType); - static LRESULT CALLBACK TrayWndProcStat(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM lParam); - LRESULT TrayWndProc(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM lParam); - static BOOL CALLBACK AboutDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); - BOOL AboutDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); - static BOOL CALLBACK PrefsDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); - BOOL PrefsDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); - static BOOL CALLBACK RunningDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); - BOOL RunningDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); - static BOOL CALLBACK FactoryResetDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); - BOOL FactoryResetDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); + static LRESULT CALLBACK TrayWndProcStat(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM param); + LRESULT TrayWndProc(HWND hwndWin, UINT uMsg, WPARAM wParam, LPARAM param); + static BOOL CALLBACK AboutDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); + BOOL AboutDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); + static BOOL CALLBACK PrefsDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); + BOOL PrefsDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); + static BOOL CALLBACK RunningDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); + BOOL RunningDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); + static BOOL CALLBACK FactoryResetDialogProcStat(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); + BOOL FactoryResetDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM param); protected: virtual void Run(); @@ -100,7 +100,7 @@ public: ~WinConsole(); virtual void Stop(); void InitAppMode(); - bool GetAppMode() { return m_bAppMode; } + bool GetAppMode() { return m_appMode; } void SetupFirstStart(); };